我是Python的新手,经过多次搜索,如何将我的列表列表转换为CSV文件后,我找不到如何纠正我的问题。
这是我的代码:
#!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)
第一个open()
将创建txt文件中的列表列表,如
list = [["hello","world"], ["my","name","is","bob"], .... , ["good","morning"]]
然后第二部分将列表列表写入csv文件,但只在第一列中。
我需要的是从这个列表列表中将它写入csv文件,如下所示:
Column 1, Column 2, Column 3, Column 4 ......
hello world
my name is bob
good morning
使用txtpad打开csv文件时恢复:
hello;world
my;name;is;bob
good;morning
答案 0 :(得分:3)
只需使用pandas dataframe
即可import pandas as pd
df = pd.DataFrame(list)
df.to_csv('filename.csv')
默认情况下,缺少的值将填入无以替换无使用
df.fillna('', inplace=True)
所以你的最终代码应该是
import pandas as pd
df = pd.DataFrame(list)
df.fillna('', inplace=True)
df.to_csv('filename.csv')
干杯!!!
注意:您不应该将list用作变量名,因为它是python中的关键字。
答案 1 :(得分:0)
我不知道这是不是你想要的:
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)
作为输出文件:
hello;world
my;name;is;bob
good;morning