Home » excel » python – Excel is not opening csv file when index=False option is selected in to_csv command

python – Excel is not opening csv file when index=False option is selected in to_csv command

Posted by: admin March 9, 2020 Leave a comment

Questions:

Hi I can export and open the csv file in windows if I do:

y.to_csv('sample.csv').

where y is a pandas dataframe.

However, this output file has an index column. I am able to export the output file to csv by doing:

y.to_csv('sample.csv',index=False)

But when I try to open the file is showing an error message:

“The file format and extension of ‘sample.csv’ don’t match. The file could be corrupted or unsafe. Unless you trust it’s source, don’t open it. Do you want to open it anyway?”

Sample of y:

enter image description here

How to&Answers:

Change the name of the ID column. That’s a special name that Excel recognizes. If the first cell of the first column of a CSV is ID, Excel will try to interpret the file as another file type. Since when you don’t exclude the index, the ID column appears in the second column, it’s fine. But when you exclude the index column, ID appears in the first cell of the first column, and Excel gets confused. You can either change the name of the column, keep the index column, or change the order of the columns in the data frame so that the ID column doesn’t appear first.