How to Turn Some Data in a Dictionary Into a CSV File Using Python
Categories: Tech | Pubby Cash Received:
Do you know how to turn some data in a dictionary into a CSV File Using Python? If you do not know how here is a way to do it. You first need to import CSV. If you don't know what CSV stands for, it stands for a comma-separated values file. After importing CSV, you need to import datetime from datetime. The datetime means what the time and the date are. Here is an example.
import csv
from datetime import datetime
After you do that, you have to open your data. You can do this using the with open method. After opening it, you have to use the read method and the eval method. Here is an example.
f_path = 'stocks.txt'
with open(f_path, 'r') as f:
content = f.read()
stocks = eval(content)
Then, you can make an empty dictionary using curly brackets. After making a dictionary, use a for loop. Make sure you use k because k stands for key and you want to use the key. Here is an example.
stocks_price = {}
for k in stocks:
stocks_price[k]=stocks[k][1]
stocks_price['Time'] = datetime.now()
After doing that, you can use another for loop to append it to your key. The append method is used to add things.
fnames = ['Time']
for k in stocks:
fnames.append(k)
Next, you need to open a CSV file as a CSV file and use set the mode equal to w. The w stands for write. Then use the DictWriter method. This method can map Python dictionaries into CSV rows. Use the writeheader method after that. This method writes the headers to the CSV file. Here is an example.
with open('stocks_history.csv', mode='w') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fnames)
writer.writeheader()
After that, use the now method. This method returns the current local date and time. The open your CSV file and make sure you set the mode to a+. The a+ means that you can open for reading and appending (writing at end of file). Finally, use the DictWriter and the writerow method. The writerow method writes a row of data into the specified file. Here is an example.
stocks_price['Time'] = datetime.now()
with open('stocks_history.csv', mode='a+') as f:
csv_writer = csv.DictWriter(f, fieldnames=fnames)
csv_writer.writerow(stocks_price)
If you did all of the above correctly, you should have turned some data in a dictionary into a CSV file.
Published from: Pennsylvania US
Liked by: H2O, Andy Tang