[英]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.