正如標題所說,我需要創建一個函式,讀取一個檔案并對該檔案中的行進行編號,跳過空白行,然后將該輸出寫入另一個檔案。這是我目前所做的,但我是個新手,所以我不確定我在做什么。
def num_lines(inputfilename, outputfilename)。
f = open(inputfilename, 'r'/span>)
lines = f.split("
")
num_lines = list()
for line in lines:
if line == " "/span>:
num_lines.append(str(len(num_lines)) " "/span> line "
")
fout = open(outputfilename, 'w')
fout.write(str("
".join(num_lines)))
fout.close()
還有一些其他的單元格,檢查你的作業,我得到的錯誤是 AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
。uj5u.com熱心網友回復:
問題是你正在打開檔案,但沒有閱讀它,所以你實際上沒有你需要的物件來將檔案分割成你想要的部分。你可以通過添加一個額外的變數來解決這個問題,比如:
g = f.read()
在你打開檔案后添加這個,然后進行修改
lines = f.split("
")
to
lines = g.split("
")
uj5u.com熱心網友回復:
@pynoob首先嘗試使用with.open()而不是普通的open。這將使你的代碼更容易遵循,并且當你忘記關閉檔案時,會導致更少的錯誤,因為它為你處理了所有這些。其次,當你用open()打開檔案時,它是一個還沒有被讀取資料的物件,所以你需要在使用它之前從它那里獲得資料。然后,你也可以使用像f-strings這樣的東西來使它變得漂亮和簡單!
def num_lines(inputfilename, outputfilename)。
page_num = 1
with open(inputfilename, 'r') as In_file:
lines = in_file.readlines()
for line in lines:
if line != '
'。
with open(outputfilename, 'a ) as out_file。
out_file.write(f'{page_num}. {line.replace("/n","")}')
page_num =1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328090.html
標籤:
