Home > Net >  List element is changing when written to csv
List element is changing when written to csv

Time:01-01

Here is my code:

outlist = ['07503503844', '07-503--503-84*', '2Unique3digitRepeats']
print(outlist)
writer.writerow(outlist)

Printing outlist results in:

['07503503844', '07-503--503-84*', '2Unique3digitRepeats']

The specific issue is with outlist[1], when written to a csv it drops the "-" characters, so in the csv it looks like:

0750350384*

Any ideas why it is different to the print output? I have already tried replacing the "-" with "*" but they are also dropped even though the one from before remains in the csv.

CodePudding user response:

Basically a csv table is a text file with comma separated strings

Following example should work:

outlist = ['07503503844', '07-503--503-84*', '2Unique3digitRepeats']
print(outlist)
with open("data.csv", "w") as f:
    f.write(",".join(outlist))

CodePudding user response:

It could be that your CSV file is changing the type of the data, which causes it to drop the dashes. So check the data type on the CSV file and make sure it is a string. Another Solution you may try is to convert your list to a dataframe then write it to CSV. So you need something like:

import pandas as pd

outlist = ['07503503844', '07-503--503-84*', '2Unique3digitRepeats']
df = pd.DataFrame(outlist)
df.to_csv('name_of_file.csv')
  • Related