写入 python 中的文件

Writing to a file in python

在下面的代码中,我只是想将我从flickr 获得的数据以一种简洁的方式写入一个文件中,以备后用。然而,尽管控制台没有抛出任何错误,但没有任何内容写入我的文件。谁能帮我解决这个问题,先谢谢了!

import flickrapi

api_key = "xxxxxxxxxxx"
secret_api_key = "xxxxxxxxxxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

def obtainImages():

    photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
    file = open("obtainedImages.txt", "w")

    for photo in photo_list[0]:
        photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])

        id = str(photo[0].attrib['id'])
        lat = str(photo_location[0][0].attrib['latitude'])
        long = str(photo_location[0][0].attrib['longitude'])

        file.write("%s" %id)
        file.write(' ')
        file.write("%s" % lat)
        file.write(' ')
        file.write("%s" % long)
        file.write('\n')

obtainImages()

这是更新后的代码,再次显示没有错误,但没有向文件写入任何内容。纬度和经度打印正常

import flickrapi

api_key = "xxxxxxxxxxxxxxxxx"
secret_api_key = "xxxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)

def obtainImages():

    photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
    file = open("obtainedImages.txt", "w")

    for photo in photo_list[0]:

        photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])
        lat = str(photo_location[0][0].attrib['latitude'])
        long = str(photo_location[0][0].attrib['longitude'])

        file.write("%s" % lat)
        file.write(' ')
        file.write("%s" % long)
        file.write('\n')

    file.close()
obtainImages()

obtainImages() 方法的末尾添加 file.close()

def obtainImages():

    photo_list = flickr.photos.search(api_key=api_key, has_geo=1, per_page = 500)
    file = open("obtainedImages.txt", "w")

    for photo in photo_list[0]:
        photo_location = flickr.photos_geo_getLocation(photo_id=photo.attrib['id'])

        id = str(photo[0].attrib['id'])
        lat = str(photo_location[0][0].attrib['latitude'])
        long = str(photo_location[0][0].attrib['longitude'])

        file.write("%s" %id)
        file.write(' ')
        file.write("%s" % lat)
        file.write(' ')
        file.write("%s" % long)
        file.write('\n')
    file.close()  ## add here

请检查以下内容

  1. 文件 obtainedImages.txt 与 python 在同一目录中 文件。
  2. 当您 运行 python 文件时,您正在关闭 & re-opening .txt 文件以检查更改
  3. 在文件周围移动光标,检查空格和换行符是否被写入,如果是,则意味着有东西 值有误

如果仍然没有得到输出,请尝试以下调试步骤:

  1. 用静态值替换latlong,看看它们是否被写入文件。
  2. 注释掉 for 循环并检查值是否写入文件(Re-indent 当您注释 for 循环时 for 块)
  3. 您正在写入的文件可能不是您正在读取的文件。因此,您可以在 阅读模式 中打开文件并尝试使用 python 脚本打印其内容。