key error : python not recognizing the names of my csv columns imported with pandas

I have coded the following code:

donnees = pd.read_csv("year_pmid_fake.csv", sep = '\t', header = 0, index_col = 0)
donnees ['year'] # year is the name of one of my columns

Anwer of Python "KeyError: 'year'"

Python is not recognizing the names of my columns.

If I mark print(donnees), ti goes well. It prints:


I would like to attach my Excel tab, but I don’t know how. So I will just write down the code I used to create my names of columns:

with open('year_pmid_fake.csv', 'w', newline='') as year_pmid_file:
    yr = csv.DictWriter(year_pmid_file, fieldnames = ["pmid", "year"], dialect="excel", delimiter=";")
    yr.writerow({"pmid": pmid, "year": year})

It created the columns names as requested.

Note that when I call back my cvs to read it, I used all possible combinations:

donnees = pd.read_csv("year_pmid_fake.csv", sep = '\t', header = 0, index_col = 0)
donnees = pd.read_csv("year_pmid_fake.csv", sep = '\t')
donnees = pd.read_csv("year_pmid_fake.csv", index_col = 0)
donnees = pd.read_csv("year_pmid_fake.csv", header = 0)
donnees = pd.read_csv("year_pmid_fake.csv", sep = '\t', header = 0)
donnees = pd.read_csv("year_pmid_fake.csv", header = 0, index_col = 0)
donnees = pd.read_csv("year_pmid_fake.csv", sep = '\t', index_col = 0)
donnees = pd.read_csv("year_pmid_fake.csv")

etc. But none of them worked so far.

Thank you very much…

Hello @nancyzloo

This post was moved to a different board that fits your topic of discussion a bit better. This means you’ll get better engagement on your post, and it keeps our Community organized so users can more easily find information.

As you’ll notice, your Topic is now in the ‘Project Development Help & Advice’ board. No action is needed on your part; you can continue the conversation as normal here.

Let me know if you have any other questions or if I can help with anything else.

Greatly appreciated,


Please see this question. read_csv does not do what you want, you should try DictReader instead.