用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 对同事简短生日祝福语