user2038763
user2038763

Reputation: 51

How can I resolve a syntax error in the file.close() in my Python code?

I'm trying to read a text file and do 2 things with every line:

A previous code worked but Python displayed garbage on my monitor

Then I tried this code and it's not working. It is complaining of a syntax error on the file.close() statement.

file = open ('C:\ASlog.txt', 'r')
output = open('C:\ASlogOUT.txt', 'w')

for line in file:
   print(str(line))
   output.write(line

file.close()
output.close()

Upvotes: 2

Views: 2424

Answers (2)

Jon Clements
Jon Clements

Reputation: 142216

If you're new to Python, especially with 3.3, you should be using with which automatically closes files:

with open('input') as fin, open('output', 'w') as fout:
    fout.writelines(fin) # loop only if you need to do something else

Which in this case is better written:

import shutil
shutil.copyfile('input filename', 'output filename')

So your complete example would be for displaying to screen and writing line to file:

with open('input') as fin, open('output', 'w') as fout:
    for line in fin:
        print(line)
        fout.write(line)

Upvotes: 0

Volatility
Volatility

Reputation: 32310

Your missing a bracket on the line before

output.write(line

should be

output.write(line)

Upvotes: 2

Related Questions