[英]Nothing writing to file in python?
Here is my code so far: 到目前为止,这是我的代码:
import flickrapi
import osmapi
import geopy
from geopy.geocoders import Nominatim
from time import sleep
api_key = "xxxxxxxxxxxxxxxxxxxx"
secret_api_key = "xxxxxxxx"
flickr = flickrapi.FlickrAPI(api_key, secret_api_key)
def obtainImages3():
file = open('citylist.txt', 'r')
file2 = open('obtainedImages.txt', 'a+')
for line in file:
fields = line.strip().split()
city = fields[1]
group_list = flickr.groups.search (api_key=api_key, text = city, per_page = 100)
for group in group_list[0]:
group_images = flickr.groups.pools.getPhotos (api_key=api_key, group_id = group.attrib['nsid'], has_geo = 1, extras = 'geo, tags, url_q')
for image in group_images[0]:
try:
photo_location = flickr.photos_geo_getLocation(photo_id=image.attrib['id'])
lat = float(photo_location[0][0].attrib['latitude'])
lon = float(photo_location[0][0].attrib['longitude'])
id = str(image.attrib['id'])
url = str(image.attrib['url_q'])
geolocator = Nominatim()
location = geolocator.reverse("{}, {}".format(lat, lon))
dict = location.raw
osmid = dict.get('osm_id', 'default_value_if_null_here')
osmtype = dict.get('osm_type', 'default_value_if_null_here')
osmaddress = dict.get('display_name', 'default_value_if_null_here')
sleep(1)
if(osmtype == 'node'):
print id
print url
print osmaddress
file2.write("%s" % id)
file2.write(' ')
file2.write("%s" % url)
file2.write(' ')
file2.write("%s" % lat)
file2.write(' ')
file2.write("%s" % lon)
file2.write(' ')
file2.write("%s" % osmaddress)
file2.write('\n')
except Exception:
pass
file2.close()
file.close()
obtainImages3()
The code is running fine without any errors and my print statements are working fine. 代码运行正常,没有任何错误,我的打印语句运行正常。 However nothing is being written to the file.
但是,没有任何内容被写入文件。 I have used the same method for writing to a file in a very similar program and it worked perfectly but here it is not working.
我已经使用了相同的方法在非常相似的程序中写入文件,并且效果很好,但是在这里却无法正常工作。 Can anyone suggest why this might be?
任何人都可以建议为什么会这样吗? Thank you!!
谢谢!!
I think the file.close() function should go into the function node, because it is in a buffer. 我认为file.close()函数应该进入函数节点,因为它位于缓冲区中。 or, remove the "except Exception:" method, and see what you got.
或者,删除“ except Exception:”方法,然后看看得到了什么。
Clearly, the file write is throwing an exception. 显然,文件写入将引发异常。 In your code, you are ignoring the exception.
在您的代码中,您将忽略该异常。 Change the except statement to:
将except语句更改为:
except Exception as e:
print e
and you will see the error. 您将看到错误。 It probably cannot open the file.
它可能无法打开文件。
Adding this so I can get credit for answer that was in comment. 添加此内容,这样我就可以对评论中的答案表示赞赏。
Try adding file2.flush()
after the file2.write('\\n')
尝试在
file2.write('\\n')
之后添加file2.flush()
file2.write('\\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.