johnsmith101
johnsmith101

Reputation: 189

Overwrite line in a file without creating the "^M" character

Say I have the python code:

print("1")
print("2")
print("3")
print("go")

which would produce the result:

1
2
3
go

If I wanted to overwrite the last line printed, I would do something like:

print("\rJohn Cena")

This would print to the console,

1
2
3
John Cena

However, If I piped that output to a text file using >, the text file would show as

1
2
3
go^MJohn Cena

How would I go about overwriting the previous line of text with a print statement, so that the output in the text file would match the output to the console?

Upvotes: 1

Views: 136

Answers (1)

DilithiumMatrix
DilithiumMatrix

Reputation: 18657

You would have to re-write the file (i.e. read it in, replace the line, and write it back out). Alternatively, you could just store what you want to write to the file (e.g. as a list), modify that as needed, and then write when you're done.

You could also consider writing in chunks: storing sections at a time while they are still changing, then writing them out at once (e.g. blocks of 10 or 100 lines).

Upvotes: 2

Related Questions