Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 行-列格式的python csv写入_Python 2.7_Python 3.x_Csv - Fatal编程技术网

Python 2.7 行-列格式的python csv写入

Python 2.7 行-列格式的python csv写入,python-2.7,python-3.x,csv,Python 2.7,Python 3.x,Csv,我有csv文件的顺序 a 1 2 3 4.56 789 B 7 8 9 4.56 1 2 3 如何将其更改为以下格式 a 12 3 4.56 789 b 7 8 9 4.56 1 2 3 其中a、b分别为第一列和第二、第三、第四列中的数字 我的代码是: with open('csv_test.csv', 'w') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow([a, b, c])

我有csv文件的顺序

a
1 2 3
4.56
789
B
7 8 9
4.56
1 2 3

如何将其更改为以下格式

a 12 3
4.56
789
b 7 8 9
4.56
1 2 3

其中a、b分别为第一列和第二、第三、第四列中的数字

我的代码是:

with open('csv_test.csv', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow([a, b, c])
    wr.writerow([1, 2, 3])
    wr.writerow([4, 5, 6])
    wr.writerow([7, 8, 9])

我注意到您正在使用csv模块

此代码读取每一行。如果该行由单个字段组成,则该字段的内容将被视为标题,并在下一行中被记住

在读取下一行之后,会写出该行的标题和内容,然后将标题替换为空字符串,因此后续行的第一列中会有一个空白字段,第二列、第三列中会有数字等

import csv
with open("infile.csv","r") as infile:
    with open("myfile.csv","w") as myfile:
        reader = csv.reader(infile) 
        wr = csv.writer(myfile)

        column1 = ""
        for fields in reader:
            if len(fields) == 1:
                column1 = fields[0]
            else:
                wr.writerow([column1]+fields)
                column1 = ""

我注意到您正在使用csv模块

此代码读取每一行。如果该行由单个字段组成,则该字段的内容将被视为标题,并在下一行中被记住

在读取下一行之后,会写出该行的标题和内容,然后将标题替换为空字符串,因此后续行的第一列中会有一个空白字段,第二列、第三列中会有数字等

import csv
with open("infile.csv","r") as infile:
    with open("myfile.csv","w") as myfile:
        reader = csv.reader(infile) 
        wr = csv.writer(myfile)

        column1 = ""
        for fields in reader:
            if len(fields) == 1:
                column1 = fields[0]
            else:
                wr.writerow([column1]+fields)
                column1 = ""