2

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"

8
  • 1
    Are you opening csv file in Excel ? Commented Jan 3, 2018 at 12:21
  • 3
    It isn't python's fault, it's Excel's. Commented Jan 3, 2018 at 12:21
  • is 10 / 2 an actual number? So is it 5 and 7? (for 28/4) Commented Jan 3, 2018 at 12:21
  • Exactly... Please try to open csv file in notepad or notepad++ or any other text editor. Commented Jan 3, 2018 at 12:22
  • 2
    Also, you don't need to call close on your file object because you are already using a context manager. Commented Jan 3, 2018 at 12:22

2 Answers 2

4

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

In Text editor I see it in numbers but in Excel I see this as dates how can I stop this from automatically converting.
That was the easy trick... You are the life saver... I am just wondering why I did not thought of putting double quotes around... ^_^ Thank you so much.
Again I am facing the problem though I had put double quotes... :( In the text editor I see every value is surrounded by double quotes... But in the sheet I get dates again. Any suggestion or help
1

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. enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.