如何在Python中删除文本文件中的行?

2024-03-29 08:49:06 发布

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

我正在尝试编写一个代码来重写.txt文件中的特定行。 我可以把我想写的那一行写下来,但我不能删除这行之前的文字。在

这是我的代码:
(我正在尝试一些事情)

def writeline(file,n_line, text):
    f=open(file,'r+')
    count=0
    for line in f:
        count=count+1
        if count==n_line :
            f.write(line.replace(str(line),text))
            #f.write('\r'+text)

您可以使用此代码来生成测试文件:

^{pr2}$

编辑:由于某些原因,如果我使用“if count==5:”代码编译正常(即使它没有删除前面的文本),但是如果我使用“if count==n_line:”,文件最终会产生大量垃圾。在

答案是可行的,但是我想知道我的代码有什么问题,以及为什么我不能读写。谢谢!在


Tags: 文件代码texttxtforifdefcount
2条回答

使用临时文件:

import os
import shutil


def writeline(filename, n_line, text):
    tmp_filename = filename + ".tmp"

    count = 0
    with open(tmp_filename, 'wt') as tmp:
        with open(filename, 'rt') as src:
            for line in src:
                count += 1
                if count == n_line:
                    line = line.replace(str(line), text + '\n')
                tmp.write(line)
    shutil.copy(tmp_filename, filename)
    os.remove(tmp_filename)


def create_test(fname):
    with open(fname,'w') as f:
        f.write('1 \n2 \n3 \n4 \n5')

if __name__ == "__main__":
    create_test('writetest.txt')
    writeline('writetest.txt', 4, 'This is the fourth line')

您正在从文件中读取并写入。别那样做。相反,您应该先写入一个^{},然后在写完并关闭原始文件后^{}。在

或者,如果保证文件的大小很小,可以使用readlines()读取所有文件,然后关闭文件,修改所需的行,然后将其写回:

def editline(file,n_line,text):
    with open(file) as infile:
        lines = infile.readlines()
    lines[n_line] = text+' \n'
    with open(file, 'w') as outfile:
        outfile.writelines(lines)

相关问题 更多 >