Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - Convert this list of lists in CSV

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
ead_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    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...