Imagine that I have a list like this :
list1 = [12.34 , 17.68 , 19.22]
Now I want to write each numbers in one row of a csv file. so after that I changed the type of numbers to string, I do this :
with open(output_file_name, 'w') as ofile:
outfile = csv.writer(ofile)
outfile.writerows(list1)
and the result will be something like this :
1,2,.,3,4
1,7,.,6,8
1,9,.,2,2
How can I do that delete these commas between the numbers?
Note :
- I want to show each number in a row 2)I don't want anything for delimiter.
- I use Python 3.9.7
- I know that .csv file might not be suitable for this case, but this is a project that somebody wants from me, as an exam !
CodePudding user response:
writerows will treat each element of the array as an row and attempt to iterate over the entries in that row, that is why for a string it splits it into individual characters. if you want to write each number on a separate line then use:
with open(output_file_name, 'w') as ofile:
outfile = csv.writer(ofile)
outfile.writerows(([str(i)] for i in list1))
CodePudding user response:
You are passing list1
as the list of rows, so the csv
module does its best to figure out what you mean.
Probably what you actually mean is
outfile.writerow(list1)
(notice the singular writerow
) which writes all the values as a single row.
Or, if you want one number per row, try
outfile.writerows([x] for x in list1)
In your attempt, list1
is converted to a list of strings, and then each string is split into a sequence to produce a row.
To reiterate, the argument to csv.writer.writerow
should be a list of cell values, and the argument to writerows
should be a list of such rows.
CodePudding user response:
Use pathlib
to easily write things
from pathlib import Path
# create file and write text
out_file = Path('example.csv')
# data
list_1 = [12.34 , 17.68 , 19.22]
out_file.write_text('column1, ')
with out_file.open(mode='a') as f:
# write to file
{f.write(f'\n{item}, ') for item in list_1}
# read contents
contents = out_file.read_text()
print(contents)
CodePudding user response:
import csv
list1 = [12.34, 17.68, 19.22]
with open('output_file_name', 'w') as ofile:
outfile = csv.writer(ofile, delimiter=" ")
outfile.writerow(list1)
This should works for You I have checked it out in editor :-D Best regards ;-)
CodePudding user response:
One quick way to do this, would be to make use of the .join() method. This method can take items from an iterator (such as your list) and join them together separated by whatever character(s) you'd like. You can do it like this to have your items separated by only a space:
with open(output_file_name, 'w') as ofile:
outfile = csv.writer(ofile)
outfile.writerows(' '.join(list1))
If you don't want a space between the items, but instead want them all stuck together do this instead:
outfile.writerows(''.join(list1))