Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to erase line from text file in Python?

Tags:

python

io

I'm trying to make a code to rewrite a specific line from a .txt file. 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.

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!

like image 578
alxg Avatar asked Apr 22 '16 05:04

alxg


People also ask

How to remove all lines from a file in Python?

The truncate () method removes all lines from a file and sets the file pointer to the beginning of the file.

How to clear a text file in Python?

As a result of studying this guide, you’ll understand how Python can clear text files and delete lines of data. Clear a Text File Using the open() Function in write Mode Opening a file in writemode will automatically delete the file’s contents.

How to delete the first and last line from a text file?

How to delete the first and last line from a text file. Please follow the below steps to delete specific lines from a text file by line number: – Read a file. Read all contents from a file into a list using a readlines () method. here each element of a list is a line from the file

How to selectively delete certain content from a file in Python?

To selectively delete certain content from the file, we need to copy the file’s contents except for those lines we want to remove and write the remaining lines again to the same file. Use the below steps to delete the first line from a file. Write all lines from a file except the first line. To delete the first N lines use list slicing.


Video Answer


2 Answers

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.

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:

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)
like image 157
John Zwinck Avatar answered Sep 21 '22 17:09

John Zwinck


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')
like image 43
Stan Zeez Avatar answered Sep 22 '22 17:09

Stan Zeez