简体   繁体   中英

How to prevent data from automatically converting into date when writing to a csv file using Python?

I have to append some rows into a csv file using python.

Here is my code.

import csv

# Variable row contains records of all users similar to this below
# ["Name", "City", "Email", "Average", "Total", "Grade", "Remarks"]


with open("file.csv", "a", newline = "") as f:
    writer = csv.writer(f)
    for item in row:
        writer.writerow(item)
f.close()

The Problem I am facing here is the "Average" is in the form of "10 / 2" or sometimes "28 / 4" etc.

The First parameter is the average score ( 10 ) and the second parameter is the number of attempts ( 2 ) for the case ( 10 / 2 ).

When I write this data using the above code to the csv file it automatically converts like this below.

"10 / 2" ---> "10 Feb"
"28 / 4" ---> "28 April"

This is not done by Python - if you open your CSV file in any text editor, you will see the data as you planned.

What is responsible for interpreting text like "28 / 2" as dates is the program were you are opening the CSV in. If it is Microsoft Excel, it is there the conversion is taking place.

Check if you have options when importing the CSV file for disabling conversion or picking the data type for each column on opening.

On the Python side, you can try enforcing quotes on all Cells. One can't guarantee that Excel will behave correctly then, but it is something you can try - create your writer with this option:

writer = csv.writer(f, quoting=csv.QUOTE_ALL)

It isn't python's fault, it's Excel's. In Excel, select a column and press ctrl+1 to select your text type. For example, select the text. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM