Python csv写入lis

2024-09-30 02:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码可以把一堆行写入csv文件。它写的是我想要的,但是。。。它在每一列中插入括号。。。 代码是:

    root_text_csv = "C:/Users/s/Desktop/text/knife"+numarul_folderelor+".csv"
    fisier_text_knife = csv.writer(open(root_text_csv,'wb'))
    row_test = []
    for filenames in os.listdir(foldere_prrra):
        knife = filenames.replace("<SP>", " ").replace(".sys", "")
        test = ['cut '+knife+' off for fuged,', 'cut '+knife+' off,', 'cut '+knife+' fool alabala,', 'cut '+knife+' nieh,', 'prrra '+knife+' alabala,',
                'cut '+knife+' fuged streaming,', 'cut '+knife+' alabala fuged,', 'cut '+knife+' off alabala,', 'prrra '+knife+' fool alabala,',
                'cut '+knife+' off fuged,', 'prrra '+knife+' niether alabala,', 'cut off '+knife+' for fuged,' 'cut '+knife+' fuged fool alabala,',
                'cut '+knife+' off niether,', 'where to cut '+knife+',', ''+knife+' fool alabala off,', 'steel '+knife+' off fuged,', 'cut '+knife+' fuged niether,',
                ''+knife+' fool alabala off,', 'fuged streaming '+knife+',', 'cut '+knife+' niether,', 'cut '+knife+' fuged,', 'red '+knife+' off,', ''+knife+' off,',
                'red '+knife+',', 'cut '+knife+',', ''+knife+' fuged,', 'fuged '+knife+',', ''+knife+' off,', 'off '+knife+',', ''+knife+',']
        random.shuffle(test)
        scris = [x for x in test if len(x) <= 30]
        row_test.append(scris) #row_test.append(scris[0])
    fisier_text_knife.writerow(row_test)

如果我将row_test.append(scris[0:7])替换为row_test.append(scris[0]),则只会从所有字符串中写入一个字符串(但不使用方括号-->;[]<;--)进行写入。在

我想写7到8行。我在这个代码上浪费了我的大脑。在

谢谢你抽出时间。在


Tags: csvtexttestforrowcutoffappend
2条回答

将写入文件的字符串与打印时相同(row_test)- 作为列表列表。在

可以使用join为每行创建一个大字符串,类似于:

row_test+= ','.join(scris) + '\n'

发生这种情况的原因是因为scris是一个列表。在

而不是:

row_test.append(scris[0:7])

不如这样做:

^{pr2}$

这也很管用(见下面的评论):

row_test.extend(scris[0:7])

如果仍然没有意义,打开一个控制台并输入下面的示例。每次更改l请将其打印出来。在

下面的示例应该向您展示为什么这样做:

l = [1,2,3]          #    l = [1,2,3]
l.extend([4,5])      #now l = [1,2,3,4,5]
l.append([6,7])      #now l = [1,2,3,4,5,[6,7]]
l.extend('hi there') #raises an exception

当您调用some_list.append(some_item)时,它将some_item放入some_list。所以如果some_item也是一个列表,那么在列表中就有一个列表。在

当您调用some_list.extend(some_item)时,它将连接到some_list的结尾。所以如果some_item不是一个列表,那么这将出错。在

编辑我想我现在明白你想要什么了。。。在

所以给定一个类似[['1','2','3'],['4','5','6'],['7','8','9']]的列表,你希望csv看起来像:123,456,789,对吗?在

而不是:

fisier_text_knife.writerow(row_test)

试试这个:

csv_friendly = [''.join(l) for l in row_test]
fisier_text_knife.writerow(csv_friendly)

相关问题 更多 >

    热门问题