用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?
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短