简体   繁体   English

使用Python写入csv文件时如何防止数据自动转换为日期?

[英]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.我必须使用 python 将一些行附加到 csv 文件中。

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.我在这里面临的问题是“平均”的形式是“10 / 2”或有时是“28 / 4”等。

The First parameter is the average score ( 10 ) and the second parameter is the number of attempts ( 2 ) for the case ( 10 / 2 ).第一个参数是平均分数 (10),第二个参数是案例 (10 / 2) 的尝试次数 (2)。

When I write this data using the above code to the csv file it automatically converts like this below.当我使用上面的代码将此数据写入 csv 文件时,它会自动转换如下。

"10 / 2" ---> "10 Feb" “10 / 2” ---> “2 月 10 日”
"28 / 4" ---> "28 April" “28 / 4”--->“4 月 28 日”

This is not done by Python - if you open your CSV file in any text editor, you will see the data as you planned.这不是由 Python 完成的 - 如果您在任何文本编辑器中打开您的 CSV 文件,您将看到您计划中的数据。

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.负责将诸如“28 / 2”之类的文本解释为日期的是您打开 CSV 的程序。如果是 Microsoft Excel,则在那里进行转换。

Check if you have options when importing the CSV file for disabling conversion or picking the data type for each column on opening.检查导入 CSV 文件时是否有选项以禁用转换或在打开时为每列选择数据类型。

On the Python side, you can try enforcing quotes on all Cells.在 Python 方面,您可以尝试在所有单元格上强制使用引号。 One can't guarantee that Excel will behave correctly then, but it is something you can try - create your writer with this option:不能保证 Excel 届时会正确运行,但您可以尝试这样做 - 使用此选项创建您的编写器:

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

It isn't python's fault, it's Excel's.这不是python的错,而是Excel的错。 In Excel, select a column and press ctrl+1 to select your text type.在 Excel 中,选择一列并按 ctrl+1 选择您的文本类型。 For example, select the text.例如,选择文本。 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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