Home > Blockchain >  My CSV file is not registering that I have a string in my code, how can I fix that?
My CSV file is not registering that I have a string in my code, how can I fix that?

Time:10-04

enter image description here input:

states = ['Michigan', 'California', 'Louisiana']
numbers = ['00','10','00']

my input was concatenated by using

for x,y in zip(states,numbers):
    print(f'{x},{y}') 

output:

Michigan,00
California,10
Louisiana,00

this output was saved as a csv file, however when I open the csv file it shows me this:

Michigan 0
California 10
Louisiana 0

shows me this in two separate columns, with states in the first column and numbers in the second column. It is not registering that the numbers are a string and need to be together in the numbers column.

It should instead look like this in the csv file:

Michigan 00
California 10
Louisiana 00

I wrote my data into the csv using:

file_data= ""
for x, y in zip(states,numbers):
    file_data  = f"{x},{y} \n "
    
#create a new file
with open("states_num.csv", "w") as f:
    f.write(file_data)

CodePudding user response:

If you are working with CSV why not to use a module like CSV?

CodePudding user response:

when I open the csv file it shows me this:

Open... In excel? That's not your actual file content since you wrote a comma in your output

There's no type information saved in csv files. Excel therefore decides to read and present data however it can, and you shouldn't rely on a GUI to tell you what's actually in a human readable text file

If you want to save excel files with type information, then don't use a CSV writer

my lists were converted into a string

You don't need that code since you already have two lists of strings that your zip() loop can use to pair the elements

CodePudding user response:

If the numbers in numbers (and thus y) are integers, f"{x},{y} \n " will write them without zero padding.

To write with f-strings and zero-padding, use formatting with a 0-prefix:

file_data= ""
for x, y in zip(states,numbers):
    file_data  = f"{x},{y:02} \n "

where the 2 is the number of places to pad to.

It's also more efficient to collect all lines in a list lines, and and ''.join(lines) in the end instead of using =. = is a little misleading in Python for strings, since it does not really mutate the LHS, but rather creates a new string with the LHS and RHS concatenated.

  • Related