Python,如何清空fi中的特定行

2024-06-17 08:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有趣的是,像这样的问题以前在SO中没有被问过。在

我正在用Python2将数据行记录到一个文本文件中。我想做的是,根据行的编号,我想删除一行,但我不希望它被下一行填满,只需保持空白(因此,不必每次删除一行时都写一个新文件)

所以我要的不是这些,

基本概念是更改特定行的内容,在本例中更改为空字符串。在

有一个问题我并不真正理解,但可能包含了我问题的答案。如果是这样的话,请帮助我理解为什么会这样。在

如果你认为我的问题是这个问题的重复,请在标记问题之前向我解释答案。在

我对这个课题的研究:

编辑:我甚至忘了问这样的事情是否可行,我将非常感谢您的信息。在


Tags: 文件数据答案infromso记录line
3条回答

你说得对,^{} module正是你所需要的:

import fileinput
def blank_line(filename, lineno):
    f = fileinput.input(files=[filename], inplace=True)
    for line in f:
        if fileinput.lineno() == lineno: # note: line numbers start at 1, not 0
            line = ""
        print line.rstrip("\n") # Output is redirected to the current line of the file
    f.close()

请注意,Python3在这里有几个优点:fileinput支持上下文管理器(with语句),而新的print()函数允许我们保持行的原样(而不是总是在末尾添加新行或空格)。在

你在找这样的东西吗?在

def remove_line_from_file(filename, line_number):
    with open(filename) as f:
        lines = f.readlines()
    lines[line_number - 1] = '\n'  # <- or whatever kind of newline is relevant for your system
    with open(filename, 'w') as f:
        f.writelines(lines)

那么,如果文件test的内容是

^{pr2}$

运行remove_line_from_file('test', 2)将把test变成

line 1

line 3

更新,现在我已经正确地阅读了这个问题:这个方法在适当的地方修改文件,用空白字符替换行的内容:

def remove_line_from_file(filename, line_number):
    with open(filename, 'r+') as f:
        count = 0
        bytes_read = 0
        while True:
            bytes_read += 1
            this_byte = f.read(1)
            if not this_byte:
                break
            if this_byte == '\n':
                count += 1
                if count == line_number - 1:
                    start = bytes_read
                elif count == line_number:
                    f.seek(start)
                    f.write(' ' * (bytes_read - start - 1))
                    break

根据pm2ring上面的评论,使用chr(127)代替{}也是有意义的。在

通过替换文件中指定行的长度来修改该行。在

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

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

q数据

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

这是密码。请注意,它使用基于1的行号。在

^{pr2}$

以下是qdata的修改版本:

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

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


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

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

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

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

相关问题 更多 >