1

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

SIM
  • 21,997
  • 5
  • 37
  • 109
  • looks like M$ Excel is interpreting the cell converting the fraction to a decimal value. But if you open `outputfile.csv` in a plain text viewer (i.e. Notepad) you should see the `csv` still contains the string `1/-1.5`. I think Excel cell formatting can be changed: see the advice in this post https://www.mrexcel.com/forum/excel-questions/909497-how-stop-excel-automatically-converting-fractions-decimals.html, "You could format the cells as 'general'." – chickity china chinese chicken Aug 12 '18 at 06:26
  • or you could consider using [xlwt](http://www.python-excel.org/) module and set the cell formatting for you; see [Format csv cells as text with python](https://www.mrexcel.com/forum/excel-questions/909497-how-stop-excel-automatically-converting-fractions-decimals.html) – chickity china chinese chicken Aug 12 '18 at 06:28
  • Ain't there any option to do the same on the fly without using any predefined format or post processing? – SIM Aug 12 '18 at 06:28
  • 1
    this is not a python problem, it's how Microsoft Excel interprets the cell data in csv files. Look at this answer's advice: [Excel CSV - Number cell format](https://stackoverflow.com/questions/137359/excel-csv-number-cell-format) – chickity china chinese chicken Aug 12 '18 at 06:33
  • Check out the update. We perhaps do it using python. – SIM Aug 12 '18 at 06:36
  • Yes, that looks like a good solution. Put it in an answer – chickity china chinese chicken Aug 12 '18 at 06:39
  • I found it working (to do the same manually) but cant find any idea to do that using python @davedwards. – SIM Aug 12 '18 at 06:44
  • sure, try `writer.writerow("'%s" % ft)` – chickity china chinese chicken Aug 12 '18 at 06:49
  • 1
    It `writer.writerow([f"'{ft}"])` did the trick as well. However, if you post it as an answer I'm ready to accept it. If anyone encounters similar issues might get help. – SIM Aug 12 '18 at 07:01

1 Answers1

2

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.