1

I am creating a simple python file in unix, just to open and write some test in it, but getting error while execution. Using Python 2.4.3

file = open(“testfile.txt”, “w”)

file.write(“This is a test”) 

file.write(“To add more lines.”)

file.close()

Error:

./test.py: line 1: syntax error near unexpected token `('
./test.py: line 1: `file = open(“testfile.txt”, “w”)'

4 Answers 4

3

I believe you are using curly quotes “” (e.g. from Microsoft Word, etc..) rather than actual single and double quote chars '' "".

Make sure you are using a regular text editor, not a rich text editor. That's the problem.

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

1 Comment

./test.py: line 1: syntax error near unexpected token (' ./test.py: line 1: file = open("testfile.txt","w") '
1

The problem is that is not a valid quote in Python. Try copying and pasting this code into your file/terminal and you should then realise the difference.

file = open("testfile.txt", "w")
file.write("This is a test")
file.write("To add more lines.")
file.close()

Comments

1

In addition to the "smart" quotes that need to be plain ASCII " characters you need a "shebang" line as the first line of the script. Otherwise it is likely to be treated as a shell script and handed to /bin/sh for execution. You should insert this as the first line of the file:

#!/usr/bin/env python

Or run it via python ./x.py.

Comments

0

I think quotes are the problem. can you try a content manager

 with open('testfile.txt', 'w') as output_file:
    output_file.write("Your Text Here")

use of context managers is to properly manage resources. In fact, that's the reason we use a context manager . The act of opening a file consumes a resource (called a file descriptor), and this resource is limited by your OS. Similarly writing. That is to say, there are a maximum number of files a process can have open at one time.

1 Comment

./test1.py: line 1: syntax error near unexpected token (' ./test1.py: line 1: with open("testfile.txt", 'w') as output_file:'

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.