5

Can anybody tell me what is wrong in this program? I face

syntaxerror unexpected character after line continuation character

when I run this program:

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");  
lines = f.readlines();

for i in lines:  
    thisline = i.split(" ");
0

3 Answers 3

12

You need to quote that filename:

f = open("D\\python\\HW\\2_1 - Copy.cp", "r")

Otherwise the bare backslash after the D is interpreted as a line-continuation character, and should be followed by a newline. This is used to extend long expressions over multiple lines, for readability:

print "This is a long",\
      "line of text",\
      "that I'm printing."

Also, you shouldn't have semicolons (;) at the end of your statements in Python.

Sign up to request clarification or add additional context in comments.

2 Comments

-1 (1) Didn't mention missing colon (2) Backslashes not needed inside [], () and {}
@John Machin: Thanks, I didn't know about (2). Fixed. I didn't want to address everything in the question, but added text about semicolon since I didn't keep it in my suggested fix.
3

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

2 Comments

actually, 1 don't use any tutorial.just search in internet and try to understand how is programming in python
Then may I suggest that you do something a bit more structured: wiki.python.org/moin/BeginnersGuide
0

The filename should be a string. In other names it should be within quotes.

f = open("D\\python\\HW\\2_1 - Copy.cp","r")
lines = f.readlines()
for i in lines:
    thisline = i.split(" ");

You can also open the file using with

with open("D\\python\\HW\\2_1 - Copy.cp","r") as f:
    lines = f.readlines()
    for i in lines:
        thisline = i.split(" ");

There is no need to add the semicolon(;) in python. It's ugly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.