用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?