【发布时间】:2016-02-19 13:17:24
【问题描述】:
我在 python 中创建了一个文本文件,我正在努力找出如何从 python 中的文本文件中打印某些行。希望可以有人帮帮我。我知道这与 f.write 或 f.read 有关。
【问题讨论】:
-
你可能错过了教程中关于Reading and Writing Files的部分。
我在 python 中创建了一个文本文件,我正在努力找出如何从 python 中的文本文件中打印某些行。希望可以有人帮帮我。我知道这与 f.write 或 f.read 有关。
【问题讨论】:
你可以试试这样的:
f = open("C:/file.txt", "r") #name of file open in read mode
lines = f.readlines() #split file into lines
print(lines[1]) #print line 2 from file
【讨论】:
with open('data.txt') as file_data:
text = file_data.read()
如果您使用 *.json 文件,好的解决方案是:
data = json.loads(open('data.json').read()))
【讨论】:
使用with关键字在打开文件后自动处理文件关闭。
with open("file.txt", "r") as f:
for line in f.readlines():
print line #you can do whatever you want with the line here
即使您的程序在执行期间中断,它也会处理文件关闭。另一种手动方式是:
f = open("file.txt", "r")
for line in f:
print line
f.close()
但请注意,仅在执行循环后才会在此处关闭。另请参阅此答案Link
【讨论】: