如何将数据保存到特定文件夹并在csv文件中添加标题行

时间:2015-04-08 15:20:26

标签: python csv dictionary save

我有一个包含以下代码的字典:

def _fetch_currencies():
    f = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
    str_f = f.readall().decode('utf-8')
    currencies_lst = json.loads(str_f)
    sorted_currencies = sorted(currencies_lst.items())
    return(sorted_currencies)

这用于从网站获取货币。

我需要使用“代码”和“名称”列保存货币,其中货币的代码和名称会保存到特定文件夹中。

我有一些用于保存的代码但是当我在其他地方需要它时它总是保存到我的python文件夹

代码如下:

def save_currencies(_fetch_currencies, filename):   
    with open(filename, 'w') as my_csv:
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.writerows(_fetch_currencies)

我也不确定如何在保存的顶部添加列标题。

2 个答案:

答案 0 :(得分:1)

首先指定要保存文件的文件夹的路径,然后在csv文件中写入标题。使用iteritems()方法迭代字典并在结尾处写下每个键和值。

def save_currencies(_fetch_currencies, filename):   
    with open("path/to/folder/{}".format(filename), 'wb') as my_csv:
       csv_writer = csv.writer(my_csv, delimiter=',')
       csv_writer.writerow(["code","name"])  
       for k,v in _fetch_currencies.iteritems(): 
          csv_writer.writerow([k,v])

答案 1 :(得分:1)

(抱歉我的英语不好)

您可以手动在文件的开头添加标题行:

def save_currencies(_fetch_currencies, filename):
    with open(filename, 'w') as my_csv:
        my_csv.write('code,name\n')   # add header line
        csv_writer = csv.writer(my_csv, delimiter=',')
        csv_writer.writerows(_fetch_currencies)

如果要更改目录,则需要在filename变量中附加路径。

记住绝对路径和相对路径之间的区别。如果您传递filename参数字符串'output.txt',它将被放置在当前目录中。将绝对路径传递到目标目录,例如:'/home/username/output.txt'或相对路径'../output.txt',用于在相对于当前python目录的父目录中写入。

要连接目录和文件名,您可以使用os.path.join函数

相关问题