I am attempting to remove instances of a character from a txt file with python using the following code:

import fileinput

for line in fileinput.FileInput("test.txt",inplace=1):
        line = line.replace("^M","")
        print line

and get the following error:

File "par.py", line 6
line = line.replace("
^
SyntaxError: EOL while scanning string literal

I am new to python and need assistance. Thank you!

Please use code tags. That line worked for me:

>>> line='dhghgjj^Mfjjggjgjg^M'
>>> line = line.replace("^M","")
>>> line
'dhghgjjfjjggjgjg'
>>>

I appreciate the example. The issue I am running into is when I try to read the file in. I think the string literal can't handle a multiple line file, and that is causing the error. Any suggestions?

File "par.py", line 6
line = line.replace("
^

Note the mark at the beginning of the line, which usually means the problem is the previous line.

## test with this first
for line in fileinput.FileInput(files="./test.txt"):
    print line
#
## iterates over the lines of all files listed in sys.argv[1:]
for line in fileinput.input():
##
## otherwise use
for line in open("./test.txt", "r"):

print line

Dupe post...Doh.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.