1

I have a Python script that is reading files as input which contains \ characters, alters some of the content, and writes it to another output file. A simplified version of this script looks like this:

inputFile = open(sys.argv[1], 'r')
input = inputFile.read()
outputFile = open(sys.argv[2], 'w')

outputFile.write(input.upper())

Given, this content in input file:

My name\'s Bob

the output is:

MY NAME\\'S BOB

instead of:

MY NAME'S BOB

I suspect that this is because of the input file's format because direct string input yields desirable results (e.g. outputFile.write(('My name\'s Bob').upper())). This does not occur for all files (e.g. .txt files work, but .js files don't). Because I am reading different files as text files, the ideal solution should not require that input file be of certain type, so is there a better way to read files? This leads me to question whether I should use different read/write functions.

Thanks in advance for all help

Sandy
  • 51
  • 1
  • 7
  • 3
    I ran your program and got `MY NAME\'S BOB`. What technique do you use to view the written file? Text editors may view the backslash as a meta character and display things differently. Just do a simple "cat" or "type" of the file to see what's really in it. – tdelaney Dec 14 '16 at 16:15
  • I also can't replicate your problem – Navidad20 Dec 14 '16 at 16:18
  • `print yourstring`, don't just look at what `yourstring` evaluates to at the REPL -- the latter prints the `repr()` form, which will will escape backslashes by doubling them, even though there's only *actually* a single backslash in the literal content. – Charles Duffy Dec 14 '16 at 16:25
  • Closely related: http://stackoverflow.com/questions/301068/python-backslash-quoting-in-string-literals/301075 – Charles Duffy Dec 14 '16 at 16:26

0 Answers0