0

I have a text file where I want to replace the character \ by ,. After reading the answer of @Jack Aidley in this SO post:

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('n', '***IT WORKED!!!***')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

I could successfully change the content such as simple letter like n into ***IT WORKED!!!***. However, if I replace

filedata.replace('n', '***IT WORKED!!!***')

by

filedata.replace('\', '***IT WORKED!!!***')

I get the syntax error:

SyntaxError: EOL while scanning string literal

How can I replace all the \ by ,?

ecjb
  • 5,169
  • 12
  • 43
  • 79
  • 1
    Python can't find the end of the string, because the backslash causes the following adjacent single-quote to get treated as an apostrophe within the string rather than the end of the string. If I want to store `you're` as a string between single-quotes, I have to type `'you\'re'`. Try `'\\'` (escaping the backslash) or `r'\'` (raw string). – dustintheglass Feb 22 '19 at 18:53
  • Great! @dustintheglass: "\\" worked! Thanks a lot! – ecjb Feb 22 '19 at 18:57
  • Possible duplicate of [Python String Replace - "\" by "/"](https://stackoverflow.com/questions/54329304/python-string-replace-by) – Ken White Feb 22 '19 at 19:21

0 Answers0