【发布时间】:2022-01-09 19:00:54
【问题描述】:
data.txt
我想用 python 读取这个文件。
【问题讨论】:
data.txt
我想用 python 读取这个文件。
【问题讨论】:
f = open('path/to/file.txt')
content = f.read()
f.close()
【讨论】:
file1 = open('data.txt', 'w')
file1.writelines("hello world")
file1.close()
file1 = open('data.txt', 'r')
Lines = file1.readlines()
如果你不明白,请随时问我一个问题。
【讨论】:
下面的 with 装饰器会在完成后自动关闭文件。
with open("data.txt", encoding='utf-8') as file:
my_data = file.read()
如果使用运行时,请确保在第二行之前包含四个空格,然后再按一次 Enter 结束 with 语句,然后键入 my_data 确认变量包含文件中的文本。
您的会话将如下所示:
>>> with open("data.txt", encoding='utf-8') as file:
... my_data = file.read()
...
>>> my_data
'This is the text in the file'
【讨论】:
使用with open() as,如下所示
_file = 'temp.txt'
with open(_file, 'r') as fyl:
ct = fyl.read()
#do something
这还有一个额外的好处,即即使发生异常也会关闭文件,因此最好使用with open() as。
【讨论】: