在python中读取和写入文件
我已经用python创建了一个文本文件,我正在努力找出如何用python打印文本文件中的某些行。希望有人能帮助我。我知道这与f.write或f.read有关。您可以尝试以下方法:在python中读取和写入文件,python,file,Python,File,我已经用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 如果您使用的是
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
如果您使用的是*.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()
但请注意,只有在执行循环之后,才会在此处关闭。另请参见此答案您可能错过了本教程中的部分。谢谢,这真的很有帮助
f = open("file.txt", "r")
for line in f:
print line
f.close()