with open('a.txt', "a+") as f:
f.seek(-2, 2) # Jump to the second last byte.
counter = 0
while counter < 2: # if found EOLS still not enough
if f.read(1) == "\n": # Count EOLs
counter += 1
f.seek(-2, 1) # jump back the read byte plus one more
position = f.tell() # save position
last_three_lines = f.read() # read last three lines
f.seek(position, 0) # jump back
f.truncate() # remove all the rest
f.write(last_three_lines[1:]) # write back necessary stuff
输入:
^{pr2}$输出:
一个简单的解决方案,使用
wc
来计算行数,sed
来进行编辑:它将在stdout上输出已编辑的文件;您可以使用
sed -i
就地编辑。在Perl的^{} 模块使得这一点变得微不足道。它的作用是将数组绑定到磁盘文件,这样对数组所做的任何更改都会反映在文件中
它看起来像这样(未经测试,因为我在我的平板电脑上发布)。输入文件的路径应作为命令行上的参数。行结束符已经从数组中出现的字符串中删除,因此调用
chop
将删除文本的最后一个字符相关问题 更多 >
编程相关推荐