【问题标题】:Cannot write to text file python 2.7 invalid syntax?无法写入文本文件 python 2.7 无效语法?
【发布时间】:2013-06-28 11:25:00
【问题描述】:

我的代码运行良好,但我希望它将值写入文本文件。当我尝试这样做时,我得到“无效的语法”。当我使用 python shell 时,它可以工作。所以我不明白为什么它在我的脚本中不起作用。

我敢打赌,这很傻,但为什么不将数据输出到文本文件??

#!/usr/bin/env python

#standard module, needed as we deal with command line args
import sys

from fractions import Fraction
import pyexiv2


#checking whether we got enough args, if not, tell how to use, and exits
#if len(sys.argv) != 2 :
#    print "incorrect argument, usage: " + sys.argv[0] + ' <filename>'
#    sys.exit(1)

#so the argument seems to be ok, we use it as an imagefile 
imagefilename = sys.argv[1]



#trying to catch the exceptions in case of problem with the file reading
try:
    metadata = pyexiv2.metadata.ImageMetadata(imagefilename)
    metadata.read();

#trying to catch the exceptions in case of problem with the GPS data reading
    try:
        latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
        latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
        longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
        longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")

        # get the value of the tag, and make it float number
        alt = float(metadata.__getitem__("Exif.GPSInfo.GPSAltitude").value)


        # get human readable values
        latitude = str(latitude).split("=")[1][1:-1].split(" ");
        latitude = map(lambda f: str(float(Fraction(f))), latitude)
        latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]

        longitude = str(longitude).split("=")[1][1:-1].split(" ");
        longitude = map(lambda f: str(float(Fraction(f))), longitude)
        longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]

        ## Printing out, might need to be modified if other format needed
        ## i just simple put tabs here to make nice columns
    print " \n A text file has been created with the following information \n"
    print "GPS EXIF data for " + imagefilename    
        print "Latitude:\t" + latitude 
        print "Longitude:\t" + longitude
        print "Altitude:\t" + str(alt) + " m"
    except Exception, e:  # complain if the GPS reading went wrong, and print the exception
        print "Missing GPS info for " + imagefilename
        print e

# Create a new file or **overwrite an existing file**
text_file = open('textfile.txt', 'w')
text_file.write("Latitude" + latitude)
# Close the output file
text_file.close()


except Exception, e:   # complain if the GPS reading went wrong, and print the exception
    print "Error processing image " + imagefilename
    print e;

我看到的错误是:

text_file = open('textfile.txt','w')
        ^
SyntaxError: invalid syntax

【问题讨论】:

  • 请务必包含您看到的实际错误。我们现在必须猜测可能出了什么问题。
  • 您似乎在混合制表符和空格。在你的脚本上运行python -tt 以计算出你的缩进在哪里去了。
  • 查看 preceding 行,确保右括号、大括号和圆括号的数量与左括号、大括号和圆括号的数量相符。
  • 另外,text_file 行的缩进也不够远。
  • 感谢大家的帮助。现在修好了。

标签: python printing gps output


【解决方案1】:

文件打开在第一个尝试块内。它在第二次尝试之外,除了块。将其移到第一个 try except 块之外或增加缩进以将它们包含在第一个 try 块中。它应该在那里工作正常。

同时在 try 中移动(增加缩进)两个打印语句。

这对你有用:

#!/usr/bin/env python

#standard module, needed as we deal with command line args
import sys

from fractions import Fraction
import pyexiv2


#checking whether we got enough args, if not, tell how to use, and exits
#if len(sys.argv) != 2 :
#    print "incorrect argument, usage: " + sys.argv[0] + ' <filename>'
#    sys.exit(1)

#so the argument seems to be ok, we use it as an imagefile 
imagefilename = sys.argv[1]



#trying to catch the exceptions in case of problem with the file reading
try:
    metadata = pyexiv2.metadata.ImageMetadata(imagefilename)
    metadata.read();

#trying to catch the exceptions in case of problem with the GPS data reading
    try:
        latitude = metadata.__getitem__("Exif.GPSInfo.GPSLatitude")
        latitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLatitudeRef")
        longitude = metadata.__getitem__("Exif.GPSInfo.GPSLongitude")
        longitudeRef = metadata.__getitem__("Exif.GPSInfo.GPSLongitudeRef")

        # get the value of the tag, and make it float number
        alt = float(metadata.__getitem__("Exif.GPSInfo.GPSAltitude").value)


        # get human readable values
        latitude = str(latitude).split("=")[1][1:-1].split(" ");
        latitude = map(lambda f: str(float(Fraction(f))), latitude)
        latitude = latitude[0] + u"\u00b0" + latitude[1] + "'" + latitude[2] + '"' + " " + str(latitudeRef).split("=")[1][1:-1]

        longitude = str(longitude).split("=")[1][1:-1].split(" ");
        longitude = map(lambda f: str(float(Fraction(f))), longitude)
        longitude = longitude[0] + u"\u00b0" + longitude[1] + "'" + longitude[2] + '"' + " " + str(longitudeRef).split("=")[1][1:-1]

        ## Printing out, might need to be modified if other format needed
        ## i just simple put tabs here to make nice columns
        print " \n A text file has been created with the following information \n"
        print "GPS EXIF data for " + imagefilename    
        print "Latitude:\t" + latitude 
        print "Longitude:\t" + longitude
        print "Altitude:\t" + str(alt) + " m"
    except Exception, e:  # complain if the GPS reading went wrong, and print the exception
        print "Missing GPS info for " + imagefilename
        print e

    # Create a new file or **overwrite an existing file**
    text_file = open('textfile.txt', 'w')
    text_file.write("Latitude" + latitude)
    # Close the output file
    text_file.close()


except Exception, e:   # complain if the GPS reading went wrong, and print the exception
    print "Error processing image " + imagefilename
    print e;

【讨论】:

  • 谢谢,现在可以使用了。你是对的。感谢您和所有提供帮助的人。
【解决方案2】:

你是不是表错了?...行:

print " \n A text file has been created with the following information \n"
print "GPS EXIF data for " + imagefilename    

列表似乎有误

编辑:您发布的代码 - 跟踪之一 - 也是错误的表格。

【讨论】:

  • 可能是 SO 上的可视化问题,因为代码使用了制表符和空格
猜你喜欢
  • 1970-01-01
  • 2020-08-17
  • 2016-01-21
  • 2017-09-28
  • 1970-01-01
  • 2014-04-29
  • 2014-09-03
  • 2014-08-21
  • 1970-01-01
相关资源
最近更新 更多