DevCon
DevCon

Reputation: 569

Replacing strings in a text file using Python adds weird characters

I want to replace a text with a path in each line of a text file using Python, but I am getting weird characters (squares) in the path in output file.

Current code:

#!/usr/bin/env python

f1 = open('input.txt', 'r')
f2 = open('output.txt', 'w')
for line in f1:
    f2.write(line.replace('test/software', 'C:\Software\api\render\3bit\sim>'))
f1.close()
f2.close()

In the output text the following in the path is replaced with a square (weird character):

Is there something wrong with my code or are the above letters reserved for the system?

Upvotes: 1

Views: 726

Answers (3)

Murkantilism
Murkantilism

Reputation: 1208

Before each of your path files, add an "r" character to create a raw string, this might fix the issue. Example:

f2.write(line.replace('test/software', r'C:\Software\api\render\3bit\sim>'))

Or alternatively, escape your backslashes:

f2.write(line.replace('test/software', 'C:\\Software\\api\\render\\3bit\\sim>'))

Upvotes: 0

CoffeeRain
CoffeeRain

Reputation: 4522

Your string has backslashes which are read in Python as escape codes. These are when a character preceded by a backslash is changed into a special character. For example, \n is a newline. You will need to either escape them (with another backslash) or just use a raw string.

r'C:\Software\api\render\3bit\sim>'

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124110

Python strings support escape codes; a backslash with certain characters is replaced by the code they represent. \r is interpreted as the ASCII line-feed character, for example, \a is an ASCII BELL, and \3 is interpreted as the ascii codepoint 3 (in octal numbering). See the Python string literal documentation.

To disable escape codes being interpreted, use a raw python string by prefixing the string definition with a r:

r'C:\Software\api\render\3bit\sim>'

so your line reads:

f2.write(line.replace('test/software', r'C:\Software\api\render\3bit\sim>'))

Alternatively, double the backslashes to have them interpreted as a literal backslashes instead:

'C:\\Software\\api\\render\\3bit\\sim>'

Upvotes: 5

Related Questions