Jason O.
Jason O.

Reputation: 3300

Python file.write inserts unintended special characters

The codes in the screenshot below does a simple regex based file string replacement, replacing two tab characters in the source text file with "TT" into the target file. The replacement works fine, but for some reason, this operation adds the weird special characters (question mark in a diamond) to the file.

How can I avoid this?

unintended special characters in the output

Upvotes: 0

Views: 186

Answers (1)

Tamas Hegedus
Tamas Hegedus

Reputation: 29896

From the documentation of file.truncate:

The current file position is not changed.

That means the system probably replaced the old contents of the file with null bytes. You have to f.seek(0) after truncating.

Upvotes: 1

Related Questions