0

(new to python here) I'm creating a simple contacts list program in python that loads and saves the list-dict to a csv file. The program should load the data on the csv to the list-dict (when it is launched) and rewrite the data (the list-dict) to the csv when the program is closed. Is there a way to read/load all the data from the csv file at once to the list-dict as the "writer.writerows(list-dict)" exists for saving the data?

def load (contacts):

with open(list,"r") as myFile:
    a = contacts
    a = myFile.read()
    print(a)

By the way, this is the outpout that I am getting:(for some reason, it seems that 'a' - that was supposed to be a list-dict - is not a list-dict) index,nome 1,asdf 2,qwer 3,xcv 4,ttt

What am I doing wrong?

TPAL
  • 3
  • 3
  • what about `myFile.readlines()`? – Leistungsabfall Sep 10 '22 at 14:14
  • I've tried it. But i coudn't put it into the list of dicts. the code looks like this now: with open("/home/x/Documents/Python/Agenda","r") as myFile: csvReader = csv.reader(myFile) for row in csvReader: agenda['index'].append(row[0]) agenda['nome'].append(row[1]) – TPAL Sep 10 '22 at 14:16
  • Using pandas might help, refer to using pandas on list of dicts in this answer https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe – drogon2 Sep 10 '22 at 14:37
  • thanks by the help, but it still seems too dificult to me to understand... – TPAL Sep 10 '22 at 15:14
  • 1) This is really something for a database. I would recommend the [sqlite](https://docs.python.org/3/library/sqlite3.html#module-sqlite3) module that is part of the Python global modules. 2) This does not need Pandas, that is overkill. 3) Look at my answer here [DictReader](https://stackoverflow.com/questions/73612757/how-to-add-headers-to-read-output-from-python-csv-file/73613277#73613277) for how to use the Python [csv](https://docs.python.org/3/library/csv.html#module-csv) module to do this. – Adrian Klaver Sep 10 '22 at 16:14
  • Thanks for the help. I am still stuck here: in the file, I already have 2 entries: 1,ttt and 2,hhh. However I am still getting {'1': '2', 'ttt': 'hhh'} by my code:with open("/home/tloet/Documents/Python/Agenda","r") as meuArquivo: reader = csv.DictReader(meuArquivo,delimiter=",", quotechar='"') for row in reader: print(dict(row)) agenda.append(dict(row)) the right output would be: {'index': 1, 'nome': 'ttt'} – TPAL Sep 13 '22 at 16:02

0 Answers0