Python在读取时截断行 [英] Python truncate lines as they are read

查看:152
本文介绍了Python在读取时截断行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序读取文件中的行,并在读取每行时运行它的魔法。一旦线被读取和正确处理,我想从文件中删除行。被删除的行的备份已被保留。我想做一些类似于

$ p $ file = open('myfile.txt','rw +')
在文件中:
processLine(line)
file.truncate(line)

这似乎是一个简单的问题,但我希望做的是正确的,而不是一个复杂的seek()和tell()调用。

也许我所有真正想要做的是从文件中删除一个特定的行。

在这个问题上花了很长时间之后,我决定每个人都可能是对的,这不是一个好做事情的方式。这似乎是如此优雅的解决方案。我正在寻找的东西类似于一个先进先出,只是让我弹出一个文件的线。

解决方案

($ myfile.txt','rw +')作为文件:

  
processLine(line)
file.truncate(0)



单独删除每行:

  lines = open('myfile.txt')。readlines()

为我行中的枚举(行[:]):
processLine(行)
del行[i]

open('myfile.txt ','w')。writelines(行)



只能留下导致异常的行:



  import fileinput 

for fileinput.input(['myfile.txt'],inplace = 1):
try:processLine(line)
除外:
sys.stdout.write(line)#打印到'myfile.txt'

一般来说,正如其他人已经说过,你试图做什么是一个坏主意。


I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like

file = open('myfile.txt', 'rw+')
for line in file:
   processLine(line)
   file.truncate(line)

This seems like a simple problem, but I would like to do it right rather than a whole lot of complicated seek() and tell() calls.

Maybe all I really want to do is remove a particular line from a file.

After spending far to long on this problem I decided that everyone was probably right and this it just not a good way to do things. It just seemed so elegant solution. What I was looking for was something akin to a FIFO that would just let me pop lines out of a file.

解决方案

Remove all lines after you've done with them:

with open('myfile.txt', 'rw+') as file:
    for line in file:
        processLine(line)
    file.truncate(0)

Remove each line independently:

lines = open('myfile.txt').readlines()

for i, line in enumerate(lines[:]):
    processLine(line)
    del lines[i]

open('myfile.txt', 'w').writelines(lines)

You can leave only those lines that cause exceptions:

import fileinput

for line in fileinput.input(['myfile.txt'], inplace=1):
    try: processLine(line)
    except:
         sys.stdout.write(line) # it prints to 'myfile.txt'

In general, as other people already said it is a bad idea what you are trying to do.

这篇关于Python在读取时截断行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆