-1

I want to write a csv file with a single column, where each row is a list of values seperated by ',' or ';', how can I do that?

Here is an example: the data [['s', [1, 2, 3]], ['a', [4, 5, 6]]]

I want a csv like this

file data

s 1;2;3

a 4,5;6

with only two column

Hao Chen
  • 145
  • 3
  • 12

2 Answers2

1

You can do that pretty easily with the join() method and generators.

Example:

data=[[1,2,3], [4,5,6]]
with open("my_file.txt", "w") as f:
  for line in data:
    f.write(",".join(str(cell) for cell in line) + "\n")

Output (cat my_file.txt):

1,2,3
4,5,6

Feel free to comment if something is unclear.

ImranD
  • 175
  • 6
  • hi, I tried this method. But is it the same to save data as int and save data as str? – Hao Chen Oct 07 '19 at 23:34
  • I think whether you save it as int or str, you will read it as str, right? – Hao Chen Oct 07 '19 at 23:35
  • Yes, it is the same. You can see a text file as a big string if it helps. I used `str()` here because `join()` requires a string. But when you'll read data from this file, it won't change anything for you. – ImranD Oct 07 '19 at 23:39
0

Well it's not gonna be a single column, there are lots of ways to do this

you can use pandas DataFrame to write your list into a csv file, write your list in a dict, then use the dict to create the csv file easily

import pandas as pd

data = {'s': [1, 2, 3], 'a':[4, 5, 6]}
df = pd.DataFrame.from_dict(data)
df.to_csv ('output.csv', index = None, header=True)

output.csv would be like :

enter image description here

Mohsen_Fatemi
  • 2,203
  • 2
  • 13
  • 23