2016-02-19 160 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