将此列表转换为CSV格式 [英] Convert this list of lists in CSV
本文介绍了将此列表转换为CSV格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Python的新手,经过几次搜索,如何将列表转换为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.
这是我的代码:
#!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文件创建列表列表,例如
The first open()
will create a list of lists from the txt file like
list = [["hello","world"], ["my","name","is","bob"], .... , ["good","morning"]]
然后,第二部分将列表列表写入csv文件中,但只写在第一列中.
then the second part will write the list of lists into a csv file but only in the first column.
我需要的是从列表列表中将其写入这样的csv文件中:
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
要在我使用txtpad打开csv文件时恢复:
To resume when I open the csv file with the txtpad:
hello;world
my;name;is;bob
good;morning
推荐答案
我不知道这是否是您想要的:
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)
提供为输出文件:
hello;world
my;name;is;bob
good;morning
这篇关于将此列表转换为CSV格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文