我是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()
Run Code Online (Sandbox Code Playgroud)
Jon*_*nts 11
要有效地获取文件的最后三行,请使用deque:
from collections import deque
with open('somefile') as fin:
last3 = deque(fin, 3)
Run Code Online (Sandbox Code Playgroud)
这样可以将整个文件读入内存,以切断您实际不想要的内容.
要反映您的评论 - 您的完整代码将是:
from collections import deque
with open('somefile') as fin, open('outputfile', 'w') as fout:
fout.writelines(deque(fin, 3))
Run Code Online (Sandbox Code Playgroud)