-1

I am a novice in Python, and after several searches about how to convert my list of lists into a CSV file, I didn't find how to correct my issue.

Here is my code :

#!C:\Python27\read_and_convert_txt.py
import csv

if __name__ == '__main__':

with open('c:/python27/mytxt.txt',"r") as t:
    lines = t.readlines()
    list = [ line.split() for line in lines ]

with open('c:/python27/myfile.csv','w') as f:
    writer = csv.writer(f)
    for sublist in list:
        writer.writerow(sublist)

The first open() will create a list of lists from the txt file like

list = [["hello","world"], ["my","name","is","bob"], .... , ["good","morning"]]

then the second part will write the list of lists into a csv file but only in the first column.

What I need is from this list of lists to write it into a csv file like this :

Column 1, Column 2, Column 3, Column 4 ......
hello     world      
my        name      is        bob
good      morning

To resume when I open the csv file with the txtpad:

hello;world
my;name;is;bob
good;morning    
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
manoman
  • 1
  • 1
  • 3

2 Answers2

6

Simply use pandas dataframe

import pandas as pd
df = pd.DataFrame(list)
df.to_csv('filename.csv')

By default missing values will be filled in with None to replace None use

df.fillna('', inplace=True)

So your final code should be like

import pandas as pd
df = pd.DataFrame(list)
df.fillna('', inplace=True)
df.to_csv('filename.csv')

Cheers!!!

Note: You should not use list as a variable name as it is a keyword in python.

Aditya
  • 352
  • 1
  • 12
0

I do not know if this is what you want:

list = [["hello","world"], ["my","name","is","bob"] , ["good","morning"]]
with open("d:/test.csv","w") as f:
    writer = csv.writer(f, delimiter=";")
    writer.writerows(list)

Gives as output file:

hello;world
my;name;is;bob
good;morning
Bart Vanherck
  • 343
  • 2
  • 10
  • Hello Bart, it works but i don't know why there is a blank line between each line. But thanks for the answer – manoman May 17 '17 at 10:17