Mini-DataBase with CSV file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Mini-DataBase with CSV file

In these days, I was looking for creating a little CSV file where I can save some inputs, so when I restart my program it will start with my CSV pre-setted loadout. I found the module csv and I've done a script like this: import csv with open('test.csv', 'w') as myFile: myFields = ['email', 'nickname', 'delay'] writer = csv.DictWriter(myFile, fieldnames=myFields) writer.writeheader() writer.writerow({'email': '[email protected]', 'nickname': 'n1', 'delay': 'low'}) It works because I can choose with what setup my program is starting and I also can change some factors easly. But there's a little problema: I don't like how it looks! In fact, It results like this: email,nickname,delay [email protected],n1,low So, is there a method to set the csv file like this instead? email, [email protected] nickname,n1 delay,low I know there's a simple method: just inverting myFields from ['email', 'nickname', 'delay'] to ['email', '[email protected]''], but it's not what I would! It seems like the csv module gives more importance to the top a column that to the start of a row. In conclusion, can I set myFields not to the top of a column but to the row's start? Thanks in advice and tell me if there are missunderstandings :)))

18th Apr 2019, 7:40 AM
Giordano Fratti
Giordano Fratti - avatar
3 Answers
+ 5
hi Giordano, i think i can understand what you mean but i can recommend to keep the file structure as it is. This is due to the CSV module. But there is another module named pandas (open source) that can handle this kind of tasks with CSV files as you are doing. It’s really worth to have a closer look on it: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-csv/#optional-python-csv-reader-parameters If i did misunderstand you please give me some feedback.
18th Apr 2019, 10:33 AM
Lothar
Lothar - avatar
+ 4
Giordano, this sounds good!
23rd Apr 2019, 5:28 PM
Lothar
Lothar - avatar
+ 2
I found a solution! This is the simple function that I've created to write an element associated with another one in a csv file: with open("settings.csv", "r") as file: settings = {rows[0]: rows[1] for rows in csv.reader(file, delimiter=",")} def write(field, data): settings[field] = data with open("settings.csv", "w") as file_csv: for key in settings.keys(): file_csv.write("%s,%s\n" % (key, settings[key])) write("email", "[email protected]")
23rd Apr 2019, 5:15 PM
Giordano Fratti
Giordano Fratti - avatar