2016-09-27 142 views
-6

我想從輸入文件讀取特定數據。我如何閱讀它?Python從輸入文件讀取數據

比如我的文件有類似的數據:

this is my first line 
this is my second line. 

所以我只是想從第二行的第一行和secon閱讀first

+4

['open'](https://docs.python.org/2/library/functions.html#open)是一個很好的起點。有關更多指導,請參閱[教程](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)。 – Kevin

+0

歡迎來到Stack Overflow!請通過[tour](http://stackoverflow.com/tour),[幫助中心](http://stackoverflow.com/help)和[如何提出一個好問題](http:// stackoverflow.com/help/how-to-ask)章節,瞭解本網站的工作原理,並幫助您改善當前和未來的問題,從而幫助您獲得更好的答案。 –

+0

StackOverflow適用於編碼問題。不適用於代碼請求。對於初學者來說,我的回答是一個例外。 –

回答

0

請根據您的需求嘗試以下代碼,但請閱讀以上註釋。

# ---------------------------------------- 
# open text file and write reduced lines 
# ---------------------------------------- 
#this is my first line 
#this is my second line. 
pathnameIn = "D:/_working" 
filenameIn = "foobar.txt" 
pathIn = pathnameIn + "/" + filenameIn 

pathnameOut = "D:/_working" 
filenameOut = "foobar_reduced.txt" 
pathOut = pathnameOut + "/" + filenameOut 

fileIn = open(pathIn,'r') 
fileOut = open(pathOut,'w') 

print(fileIn) 
print(fileOut) 

i = 0 

# Save all reduced lines to a file. 
for lineIn in fileIn.readlines(): 
    i += 1 # number of lines read 
    lineOut = lineIn[11:16] 
    fileOut.writelines(lineOut +"\n") 

print("*********************************") 
print("gelesene Zeilen: " + str(i)) 
print("*********************************") 

fileIn.close() 
fileOut.close() 
+0

我正在運行代碼。但它是給我語法錯誤,當我檢查字符與'第一' fileIn =打開(「test.txt」,'r') lineIn in fileIn.readlines(): i + = 1#行數閱讀 K = LINEIN [3:9] 如果k = '第一': 打印(K) 其他: 打印( '錯誤') – ankit

+0

@ankit - 通過評論上述請及時清理你的問題。 –