简体   繁体   中英

How to save data to a specific folder and add header line in csv file

I have a dictionary with the following code:

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)

This is used to fetch currencies from a website.

I need to save the currencies with columns "code" and "name" in which the currencies' codes and names are saved to a specific folder.

I have some code for saving but it always saves to my python folder when i need it elsewhere

the code is as follows:

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)

I am also not sure how to add the column titles at the top of the save.

First assign the path to the folder you want to save the file, then write the headers in the csv file. Using the iteritems() method you iterate through your dictionary and write each key and value at the end.

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

(Sorry for my bad English)

You can add header line in begin of your file manually:

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)

If you want to change directory, you need to append path to it in filename variable.

Remember the difference between absolute and relative paths. If you pass as filename argument string 'output.txt' it will be placed in current directory. Pass absolute path to target directory, for example: '/home/username/output.txt' or relative path '../output.txt' for write in parent directory relative to current python directory.

To concatenate directory and filename you can use os.path.join function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM