0

I am learning Python programming and after follow the falling tutorial at http://www.qgistutorials.com/en/docs/getting_started_with_pyqgis.html when typing the follow script

output_file = open('c:/Documents/test/airports.txt', 'w')
for f in layer.getFeatures():
    geom = f.geometry()
    line = '%s, %s, %f, %f\n' % (f['name'], f['iata_code'],geom.asPoint().y(), geom.asPoint().x())
    unicode_line = line.encode('utf-8')
    output_file.write(unicode_line)
 output_file.close()

I am getting the following errors:

output_file = open('c:/Documents/test/airports.txt', 'w')
Traceback (most recent call last):
File "<input>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'c:/Documents/test/airports.txt'

for f in layer.getFeatures():
    geom = f.geometry()
    line = '%s, %s, %f, %f\n' % (f['name'], f['iata_code'],
    geom.asPoint().y(), geom.asPoint().x())
    unicode_line = line.encode('utf-8')
    output_file.write(unicode_line)
output_file.close()

File "<input>", line 7
output_file.close()
SyntaxError: invalid syntax

Can someone tell me the correct way to fix this?

  • 1
    You have a space before " output_file.close()". Python uses indentation/whitespace as part of the syntax. Change it to output_file.close() – user2856 Oct 30 '17 at 3:28
  • did you create the airports.txt file before write on it ? – Hugo Roussaffa - GeoDatup Oct 30 '17 at 9:06
1

No such file or directory: 'c:/Documents/test/airports.txt'

Suggests that the path 'c:/Documents/test/' does not exist or that you do not have write permissions

File "", line 7 output_file.close() SyntaxError: invalid syntax

Test with an additional newline

output_file = open('c:/Documents/test/airports.txt', 'w')
for f in layer.getFeatures():
    geom = f.geometry()
    line = '%s, %s, %f, %f\n' % (f['name'], f['iata_code'],geom.asPoint().y(), geom.asPoint().x())
    unicode_line = line.encode('utf-8')
    output_file.write(unicode_line)

output_file.close()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.