简体   繁体   English

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

[英]How to erase line from text file in Python?

I'm trying to make a code to rewrite a specific line from a .txt file. 我正在尝试创建一个代码来重写.txt文件中的特定行。 I can get to write in the line i want, but i can't erase the previous text on the line. 我可以写在我想要的行,但我不能删除行上的前一个文本。

Here is my code: 这是我的代码:
(i'm trying a couple of things) (我正在尝试几件事)

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)

You can use this code to make a test file for testing: 您可以使用此代码制作测试文件以进行测试:

with open('writetest.txt','w') as f:
    f.write('1 \n2 \n3 \n4 \n5')

writeline('writetest.txt',4,'This is the fourth line')

Edit: For Some reason, if i use 'if count==5:' the code compiles ok (even if it doen't erase the previous text), but if i do 'if count==n_line: ', the file ends up with a lot of garbage. 编辑:由于某些原因,如果我使用'if count == 5:'代码编译好(即使它不删除前一个文本),但如果我'如果count == n_line:',则文件结束垃圾很多。

The Answers work, but i would like to know what are the problems with my code, and why i can't read and write. 答案工作,但我想知道我的代码有什么问题,以及为什么我不能读写。 Thanks! 谢谢!

You are reading from the file and also writing to it. 您正在读取文件并写入文件。 Don't do that. 不要那样做。 Instead, you should write to a NamedTemporaryFile and then rename it over the original file after you finish writing and close it. 相反,您应该写入NamedTemporaryFile ,然后在完成写入并关闭它之后renamerename为原始文件。

Or if the size of the file is guaranteed to be small, you can use readlines() to read all of it, then close the file, modify the line you want, and write it back out: 或者,如果文件的大小保证很小,您可以使用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)

Use temporary file: 使用临时文件:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM