user15291990
user15291990

Reputation:

Wierd null characters when writing to a text file

I was writing a function that replaces a single line in a text file to a user inputted one.

def file_redact(file_name: str):
    line_to_replace = int(input('Enter the line to replace (starting from 1): '))
    f = open(file_name, 'r+')
    file_data = f.readlines()
    file_data[line_to_replace - 1] = input('Write a new line:\n') + '\n'
    f.truncate(0)
    f.writelines(file_data)
    f.close()

The function does this just fine, however, it also adds null characters to the beginning of the file.

This is how the file looks like after I've replaced the first line:

\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00Replaced text

Sample text2

Sample text3

Sample text4

Sample text5

Any help is appreciated, especially if there's a better way to implement this.

Upvotes: 5

Views: 1303

Answers (3)

TheEagle
TheEagle

Reputation: 5982

I think you misunderstood what file.truncate does. It resizes the file, and obviously fills it with zero bytes or something. What you want is file.seek, which seeks the current write and read position to the given number. Alone, this could give problems when the replacement line is shorter than the original one, so you should use both file.seek and file.truncate. This code works:

def file_redact(file_name: str):
    line_to_replace = int(input('Enter the line to replace (starting from 1): '))
    f = open(file_name, 'r+')
    file_data = f.readlines()
    file_data[line_to_replace - 1] = input('Write a new line:\n') + '\n'
    f.truncate(0)
    f.seek(0)
    f.writelines(file_data)
    f.close()
file_redact("test.txt")

Upvotes: 2

Scott Hunter
Scott Hunter

Reputation: 49920

It would be more straight-forward to open the file for reading ('r' mode) to read it and then re-open it for writing ('w' mode) to write to it.

Upvotes: 1

Unspoiled9710
Unspoiled9710

Reputation: 102

Try removing the "\n" from the input line:

file_data[line_to_replace - 1] = input('Write a new line: )

Upvotes: -3

Related Questions