Search code examples
pythonfileiochar

How to delete a symbol from file by its position


I need to delete a symbol from txt file by its position in file. For example, there is a text file sample.txt:

Hello, world!
Abcdef
hello
world

and I need to delete a character , that is located on the sixth position: pos = 6

I tried to use this code:

pos = 6

with open('sample.txt', 'r+') as f:
    f.seek(pos - 1) # move to the position before ,
    print(f.read(1)) # print the , character
    f.seek(pos - 1) # return back to the position before ,
    f.write('\r')
    f.close()

This prints ,, like I expected but file now looks like this:

Hello
 world!
Abcdef
hello
world

So my code replaced the , character with a new line symbol \n, instead of carriage return symbol \r.

UPD:

My solution replaces the , symbol with symbol with ASCII code 13 (0D), that doesn't solve my problem:

gggg


Solution

  • VSCode is showing the CR as a newline.

    To remove it entirely, don't overwrite it with a single character. Read the rest of the file into a variable, seek back to the position, then overwrite from the variable.

    pos = 6
    
    with open('sample.txt', 'r+') as f:
        f.seek(pos - 1) # move to the position before ,
        print(f.read(1)) # print the , character
        rest = f.read() # read the rest of the file
        f.seek(pos - 1) # return back to the position before ,
        f.write(rest)
        f.truncate() # adjust the end of the file
    

    BTW, you don't need f.close(), that's done automatically when you use with.