I want to write a function that check/write a .csv file to stock data about the setting of the user like his username and some other preferences. How can I do that efficiently?
I tried so many thing that I delete but it always created the file and it’s empty. I want it to be a dictionary so I just need a key to access the data I need like: {‘username’: ‘Steeve’}.
What is the best way to do this?
(this is just there as an example but is definitely not working and I didn’t saved all my past attempts)
def settings(filename, decision):
settings_dict = {}
username = 'username'
with open(filename, 'w') as csv_file:
reader = csv.reader(csv_file)
writer = csv.writer(csv_file)
for row in reader:
if row == ['username', 'none']:
entry_exists = True
break
# Append the entry if it doesn't exist
if not entry_exists:
with open(filename, mode='a', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['username', 'none'])
a think that the pandas module is well suited for this. Here is a link to a basic tutorial. There are many others of course of which you can do your own search but this should get you started and familiar with how to start using it.
If you want only to read from the file, open it for reading (mode is 'r'). That’s the default mode. It’ll raise an exception if the file doesn’t already exist.
If you want to append to the file, open it for appending (mode is 'a'). If the file doesn’t already exist, it’ll be created.
Here is a simple script using the Pandas library module where we create a .csv file named some_test_file.csv file. We save it to a folder located on the Desktop.
import pandas as pd
# Create folder to save test .csv file to
newpath = r'C:\Desktop\Temp_Directory'
if not os.path.exists(newpath):
os.makedirs(newpath)
# Define column titles
col_titles = ['TICKER', 'PRICE', 'DIVIDEND']
# Define data to be displayed under column titles
data = [[' AMD', 145.25, 1.25],
[' TSLA', 198.23, 2.85],
[' GOOG', 758.12, 1.74],
[' INTL', 59.63, 1.05],
[' MSFT', 36.85, 3.45],
[' IBM', 74.08, 1.61]]
# Create panda dataframe with data and column titles
df = pd.DataFrame(data, columns = col_titles)
# Print the dataframe to the console for test verification purposes
print('\n', df)
# Create a blank .csv file with absolute directory path
csv_path = 'C:/Desktop/Temp_Directory/some_test_file.csv'
# Write info to the .csv file:
with open(csv_path, 'w', encoding = 'UTF-8') as csv_file:
df.to_csv(csv_file)
It is rather simple to read individual cell data from .csv files using pandas. If you think that you will be working with .csv files on a regular basis, this is a library package worth learning.