[英]How to save data to a specific folder and add header line in csv file
我有一本包含以下代码的字典:
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)
我也不确定如何在保存的顶部添加列标题。
首先将路径分配到要保存文件的文件夹,然后将头文件写入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])
(对不起,我的英语不好)
您可以在文件开头手动添加标题行:
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'
或相对路径'../output.txt'
,以相对于当前python目录的父目录进行写入。
要连接目录和文件名,可以使用os.path.join
函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.