-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    
3
  • strange as default separator is comma, not semicolon. But whatever: can you try: writer = csv.writer(f,delimiter="\t") Commented May 17, 2017 at 9:11
  • note: use writer.writerows(list) directly. And don't use list as a variable name Commented May 17, 2017 at 9:12
  • This can't be your actual indentation. This won't run. Please fix your indentation. Commented May 17, 2017 at 9:14

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Hello Bart, it works but i don't know why there is a blank line between each line. But thanks for the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.