SIM
SIM

Reputation: 22440

strings converted to floats in a csv file

When I write a certain fraction in a csv file it gets automatically calculated whereas my requirement is to keep it as it is.

This is my try:

import csv

ft = "-1/-1.5" #or -1/-1.5 (removing the quotes)
print(ft)

with open("outputfile.csv","w",newline="") as infile:
    writer = csv.writer(infile)
    writer.writerow([ft])

Console prints it when in quotes:

-1/-1.5

However, when I write them same in a csv file it becomes like the following no matter when I try using quotes or without quotes.

0.666666667

How can I write the same in a csv file like -1/-1.5?

See the image below (this is what I'm getting right now):

enter image description here

If i try use a ' in a cell and then write the value, the output serves the purpose. Can I not do it programmatically?

enter image description here

Upvotes: 1

Views: 627

Answers (1)

As OP mentioned in comments use:

writer.writerow([f"'{ft}"])

will add formatting to the csv output file so M$ Excel will display the string values in string ft retaining their original string format.

Upvotes: 2

Related Questions