2016-02-19 195 views
-5

我在python中创建了一个文本文件,我正在努力研究如何从python中的文本文件打印某些行。希望可以有人帮帮我。我知道它与f.write或f.read有关。从python中读取和写入文件

+2

可能重复[Python:逐行读入文件到数组中](http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array ) – 2016-02-19 13:19:16

+1

您可能错过了本教程中有关[读写文件](https://docs.python.org/3.5/tutorial/inputoutput.html#reading-and-writing-files)的部分。 – Matthias

回答

0

你可以尝试这样的事:

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 
+0

谢谢,这真的有帮助 – H14

0
with open('data.txt') as file_data: 
    text = file_data.read() 

如果您正在使用*上传.json文件很好的解决方案是:

data = json.loads(open('data.json').read())) 
0

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