gpt4 book ai didi

python - 在python中写入文件

转载 作者:行者123 更新时间:2023-11-28 22:39:20 25 4
gpt4 key购买 nike

在下面的代码中,我只是想将我从 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

关于python - 在python中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com