We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,039 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Python: Parsing Text from a file and getting a SyntaxError

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!

3
Contributors
4
Replies
11 Hours
Discussion Span
1 Year Ago
Last Updated
5
Views
bellarc
Newbie Poster
2 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Please use code tags. That line worked for me:

>>> line='dhghgjj^Mfjjggjgjg^M'
>>> line = line.replace("^M","")
>>> line
'dhghgjjfjjggjgjg'
>>>
pyTony
pyMod
Moderator
6,306 posts since Apr 2010
Reputation Points: 879
Solved Threads: 986
Skill Endorsements: 26

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?

bellarc
Newbie Poster
2 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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

woooee
Posting Maven
2,706 posts since Dec 2006
Reputation Points: 827
Solved Threads: 779
Skill Endorsements: 9

Dupe post...Doh.

woooee
Posting Maven
2,706 posts since Dec 2006
Reputation Points: 827
Solved Threads: 779
Skill Endorsements: 9

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0651 seconds using 2.67MB