用Python编写,读取文件内容
先决条件:打开,关闭文件/open(),close()在Python功能
1)编写内容(使用file_)object.write()
要在文件中写入内容,我们使用write()函数,该函数与文件对象名称一起调用。
语法:
file_object.write(data)
2)读取内容(使用file_)object.read()
要读取文件的内容,我们使用read()函数,该函数与文件对象名称一起调用。
语法:
file_object.read()
它以字符串格式返回文件的内容。
示例
在这里,我们正在创建文件,将数据写入文件,关闭文件,然后再次以只读模式读取文件,读取数据,关闭文件。
#以写模式打开文件
fo = open("data.txt","wt")
#要写入文件的数据
data = "Hello friends, how are you?"
#将数据写入文件
fo.write(data)
#关闭档案
fo.close()
print("Data is written and file closed.")
#清除变量
data = ""
#以读取模式打开文件
fo = open("data.txt","rt")
#读取数据并打印
data = fo.read()
print("file's content is: ")
print(data)
#关闭档案
fo.close()输出结果
Data is written and file closed. file's content is: Hello friends, how are you?
热门推荐
10 每年春节祝福语大全简短
11 升学宴同学祝福语简短
12 姐妹生日祝福语女孩简短
13 调皮祝福语老师文案简短
14 生日贺卡祝福语简短创意
15 发文章祝福语简短英语
16 小学同学简短祝福语
17 写给女友的祝福语++简短
18 国庆中秋祝福语大全简短