Python,如何清空文件中的特定行 [英] Python, How to empty a specific line in file

查看:212
本文介绍了Python,如何清空文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在Python2中将数据行记录到文本文件中。我想要做的是,通过行数,我想删除一行,但我不希望它填充下一个,只是保持空(因此不必每次写一个新的文件擦掉一条线。)



所以我所要求的不是其中之一,



基本概念是更改特定内容



有一个问题,我没有真正理解,但可以包含我的问题的答案。如果是这样的话,请帮我理解一下。



如果您认为我的问题与此相同,请在解答问题之前向我解释答案。我对这个问题的研究:



编辑:我甚至忘了问这样一个事情是可行的,我会感谢您的信息。

解决方案

函数,用于在原地修改文本文件,用相同长度的行替换指定的行。

在这个演示中,我使用作为替换字符,以便更容易地看到发生了什么。您可以使用简单的空格( chr(32)),或者使用ASCII DEL字符( chr(127) == \x7f )。使用DEL的一个好处是,它可以快速删除所有这些已擦除行,因为这个字符不会出现在任何文件的正确行中,因此更容易一些。



首先,这里有一个小文本文件来测试这个代码。



qdata

  1 one 
2 two
3 three
4 four
5 five
6 six
7 7
8
9

以下是代码。请注意,它使用基于1的行号。

  def erase_line(fname,line_num):
'''In使用
a替换文件`fname`中的行`line_num`替换同一长度的DEL字符的行,保留新行。
'''
DEL ='#'
打开(fname,'r +')作为f:
在范围内(line_num - 1):
f.readline()
start = f.tell()
line = f.readline()
line = DEL *(len(line) - 1)+'\\\
'
f.seek(start)
f.write(line)

erase_line('qdata',3)
$ b

以下是 qdata 的修改版本:

  1 one 
2 two
#######
4 four
5 five
6 six
7 seven
8八
9九

因为它必须处理不同长度的行, erase_line 必须读取所有的行,直到找到所需的行,但只重写该行,不会修改任何其他行,所以它应该相当快。如果您的线路长度固定,我们可以使用 .skip 立即跳转到所需的线路。




这是一个函数,它将删除完全由DEL字符组成的所有行,并将结果写入一个新文件。

pre > def compact(oldname,newname):
'''将文件`oldname`复制到`newname`,删除
完全由DEL字符组成的行,除了' \\\
'
'''
DEL ='#'
以open(oldname,'r')作为fin,open(newname,'w')作为fout:$ b $如果不是line.lstrip(DEL)=='\\\
':
fout.write(line)
$ b $ compact('qdata', 'qdata.new')

qdata.new

  1一个
2两个
4四个
5五
6六
7七个
八个
9个

最后,这是一个执行压缩操作的Unix / Linux管道,假定您使用的是实际的DEL字符(八进制为 \177 )。这可能比我的Python版本快。

  tr -d'\177'< qdata | awk'!/ ^ $ /'> qdata.new 


It is interesting that a question like this is not asked before in SO.

I am recording lines of data in to a text file in Python2. What I would like to do is, by the number of the line, I want to erase a line, but I don't want it filled by the next one, just stay empty (Therefore not having to write a new file each time I erase a line.)

So what I am asking is not one of these,

Basic concept is to change contents of a specific line, which in this case changed with an empty string.

There is a question which I did not truly understand, but could contain an answer for my question. If it is such, please help me understand how so.

If you think my question is a duplicate of this one, please explain the answer to me, before flagging he question.

My research on the subject:

Edit: I even forgot to ask if such a thing is feasible, I would appreciate your information.

解决方案

Here's a function that modifies a text file in-place, replacing the specified line by a line of the same length.

In this demo I use # as the replacement character to make it easier to see what's going on. You could use a simple space (chr(32)) instead, or the ASCII DEL character (chr(127) == \x7f). A benefit of using DEL is that it makes it a little easier to rapidly delete all of these "erased" lines because that character won't occur in any of the file's "proper" lines.

Firstly, here's a small text file to test this code with.

qdata

1 one
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
9 nine

Here's the code. Note that it uses 1-based line numbering.

def erase_line(fname, line_num):
    ''' In-place replacement of line `line_num` in file `fname` with
        a line of DEL chars of the same length, retaining the newline.
    '''
    DEL = '#'
    with open(fname, 'r+') as f:
        for i in range(line_num - 1):
            f.readline()
        start = f.tell()
        line = f.readline()
        line = DEL * (len(line) - 1) + '\n'
        f.seek(start)
        f.write(line)

erase_line('qdata', 3)

Here's the modified version of qdata:

1 one
2 two
#######
4 four
5 five
6 six
7 seven
8 eight
9 nine

Because it has to deal with lines of varying lengths, erase_line has to read all of the lines until it finds the desired one, but it only re-writes that line, it doesn't modify any other lines, so it should be fairly quick. If your lines were of fixed length we could use .skip to immediately jump to the desired line.


Here's a function that will strip any lines that consist entirely of the DEL character, writing the result to a new file.

def compact(oldname, newname):
    ''' Copy file `oldname` to `newname`, removing lines that
        consist entirely of the DEL char, apart from the '\n'
    '''
    DEL = '#'
    with open(oldname, 'r') as fin, open(newname, 'w') as fout:
        for line in fin:
            if not line.lstrip(DEL) == '\n':
                fout.write(line)

compact('qdata', 'qdata.new')

qdata.new

1 one
2 two
4 four
5 five
6 six
7 seven
8 eight
9 nine

Finally, here's a Unix / Linux pipeline that performs the compacting operation, assuming you're using the actual DEL character (which is \177 in octal). It's probably faster than my Python version.

tr -d '\177' <qdata | awk '!/^$/' >qdata.new

这篇关于Python,如何清空文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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