[英]Copy the last three lines of a text file in python?
我是python的新手,它處理變量和列表中變量數組的方式對我來說很陌生。 我通常會將一個文本文件讀入一個向量,然后通過確定向量的大小將最后三個文件復制到一個新的數組/向量中,然后使用for循環將最后一個size-3的復制函數循環到一個新數組中。
我不明白循環如何在python中工作所以我不能這樣做。
到目前為止我有:
#read text file into line list
numberOfLinesInChat = 3
text_file = open("Output.txt", "r")
lines = text_file.readlines()
text_file.close()
writeLines = []
if len(lines) > numberOfLinesInChat:
i = 0
while ((numberOfLinesInChat-i) >= 0):
writeLine[i] = lines[(len(lines)-(numberOfLinesInChat-i))]
i+= 1
#write what people say to text file
text_file = open("Output.txt", "w")
text_file.write(writeLines)
text_file.close()
要有效地獲取文件的最后三行,請使用deque
:
from collections import deque
with open('somefile') as fin:
last3 = deque(fin, 3)
這樣可以將整個文件讀入內存,以切斷您實際不想要的內容。
要反映您的評論 - 您的完整代碼將是:
from collections import deque
with open('somefile') as fin, open('outputfile', 'w') as fout:
fout.writelines(deque(fin, 3))
只要您可以將所有文件行保存在內存中,就可以對行列表進行切片以獲取最后的x項。 請參閱http://docs.python.org/2/tutorial/introduction.html並搜索“切片表示法”。
def get_chat_lines(file_path, num_chat_lines):
with open(file_path) as src:
lines = src.readlines()
return lines[-num_chat_lines:]
>>> lines = get_chat_lines('Output.txt', 3)
>>> print(lines)
... ['line n-3\n', 'line n-2\n', 'line n-1']
首先回答你的問題,我的意思是你有一個索引錯誤,你應該用writeLine.append()替換writeLine [i]行。 之后,您還應該執行循環來編寫輸出:
text_file = open("Output.txt", "w")
for row in writeLine :
text_file.write(row)
text_file.close()
我可以建議用更pythonic的方式來寫這個嗎? 它將如下:
with open("Input.txt") as f_in, open("Output.txt", "w") as f_out :
for row in f_in.readlines()[-3:] :
f_out.write(row)
可能的解決方案:
lines = [ l for l in open("Output.txt")]
file = open('Output.txt', 'w')
file.write(lines[-3:0])
file.close()
如果您不了解python語法,這可能會更清楚一些。
lst_lines = lines.split()
這將創建一個包含文本文件中所有行的列表。
然后你可以做最后一行:
last = lst_lines [-1] secondLAst = lst_lines [-2] etc ...列表和字符串索引可以從末尾到達' - '。
或者你可以使用以下方法遍歷它們並打印特定的:
for i in range(start,stop-1,step):string = lst_lines [i]
然后將它們寫入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.