How can I avoid python converting big numbers to scientific notation?
Question:
I have data structured as follows:
['1404407396000',
'484745869385011200',
'0',
'1922149633',
"The nurse from the university said I couldn't go if I don't get another measles immunization...",
'-117.14384195',
'32.8110777']
I want to write this data to a csv file, but when I do, python converts the numbers to scientific notation (e.g 1.404E12).
I am using the following function to convert the list of lists to a csv:
def list_to_csv(data,name_of_csv_string):
import csv
"""
This function takes the list of lists created from the twitter data and
writes it to a csv.
data - List of lists
name_of_csv_string - What do you think this could be?
"""
with open(name_of_csv_string + ".csv", "wb") as f:
writer=csv.writer(f)
writer.writerows(data)
How can I avoid this?
Answers:
By using the format specification mini language described here:
https://docs.python.org/2/library/string.html
Search for: 7.1.3.1. Format Specification Mini-Language
Use string formatting.
writer.writerows("%f" % data)
There are various formatting options you can check out here.
In my case, it was the Microsoft Excel app which was converting the numbers to scientific notation (even in the formula bar the numbers were in scientific notation).
Try opening the csv file using Notepad or a standard text editor to make sure if the numbers are saved as integers. In my case, the Notepad showed normal integer numbers, while it was Excel which showed them in the Scientific Notation form.
I have data structured as follows:
['1404407396000',
'484745869385011200',
'0',
'1922149633',
"The nurse from the university said I couldn't go if I don't get another measles immunization...",
'-117.14384195',
'32.8110777']
I want to write this data to a csv file, but when I do, python converts the numbers to scientific notation (e.g 1.404E12).
I am using the following function to convert the list of lists to a csv:
def list_to_csv(data,name_of_csv_string):
import csv
"""
This function takes the list of lists created from the twitter data and
writes it to a csv.
data - List of lists
name_of_csv_string - What do you think this could be?
"""
with open(name_of_csv_string + ".csv", "wb") as f:
writer=csv.writer(f)
writer.writerows(data)
How can I avoid this?
By using the format specification mini language described here:
https://docs.python.org/2/library/string.html
Search for: 7.1.3.1. Format Specification Mini-Language
Use string formatting.
writer.writerows("%f" % data)
There are various formatting options you can check out here.
In my case, it was the Microsoft Excel app which was converting the numbers to scientific notation (even in the formula bar the numbers were in scientific notation).
Try opening the csv file using Notepad or a standard text editor to make sure if the numbers are saved as integers. In my case, the Notepad showed normal integer numbers, while it was Excel which showed them in the Scientific Notation form.