没有在python中写入文件?

时间:2016-02-10 15:34:04

标签: python file

到目前为止,这是我的代码:

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()

代码运行正常,没有任何错误,我的打印语句工作正常。但是没有任何内容写入文件。 我使用相同的方法在一个非常类似的程序中写入文件,它工作得很好,但在这里它不起作用。任何人都可以建议为什么会这样?谢谢!!

3 个答案:

答案 0 :(得分:3)

我认为file.close()函数应该进入函数节点,因为它在缓冲区中。或者,删除“异常:除外”方法,看看你得到了什么。

答案 1 :(得分:3)

显然,文件写入会引发异常。在您的代码中,您忽略了异常。将except语句更改为:

except Exception as e:
    print e

你会看到错误。它可能无法打开文件。

答案 2 :(得分:2)

添加此内容,以便我可以为评论中的答案赢得赞誉。

尝试在file2.flush()

之后添加file2.write('\n')