0

我想在我的 CSV 文件中附加一个新行但是新行必须用逗号分隔,并且它们之间有空格。我只能用逗号或空格分隔它们。

当前文件是:

数据.csv

1,abc1,xyz1
2,abc2,xyz2
3,abc3,xyz3
4,abc4,xyz4
5,abc5,xyz5

我想要它:

数据.csv

1, abc1, xyz1
2, abc2, xyz2
3, abc3, xyz3
4, abc4, xyz4
5, abc5, xyz5

我编写 CSV 的代码:

my_new_row = [6, 'abc6', 'xyz6']
with open('data.csv', 'a', newline='') as filehandle:
    writer = csv.writer(filehandle, delimiter=',')
    writer.writerow(my_new_row)
4

5 回答 5

0

您要打印的格式似乎不是标准的 CSV 格式。因此,您可以编写自己的编写器来打印该字符串格式。

逗号分隔值 (CSV) 文件的通用格式和 MIME 类型

于 2020-08-06T06:43:37.267 回答
0

这当然不是很有效,但它确实解决了您的问题,只有新行在分隔符后包含空格。

import csv

my_new_row = [6, 'abc6', 'xyz6']
x, y = ',', ', '

with open('data.csv', 'r', newline='') as original_file:
    original_reader = csv.reader(original_file)
    with open('new_file.csv', 'w', newline='') as new_file:
        new_writer = csv.writer(new_file, delimiter=',')
        for line in original_reader:
            new_writer.writerow(line)
        with open('temp_file.csv', 'w+', newline='') as temp_file:
            temp_reader = csv.reader(temp_file)
            temp_writer = csv.writer(temp_file, delimiter=',')
            temp_writer.writerow(my_new_row)
            temp_file.seek(0)
            data = temp_file.read()
            temp_file.seek(0)
            temp_file.write(data.replace(x, y))
            temp_file.seek(0)
            for line in temp_reader:
                new_writer.writerow(line)

输出全部写入 new_file.csv

于 2020-08-06T06:46:41.927 回答
0

AS CVS 文件格式意味着“,”逗号分隔值,我假设您现在不再需要 CSV 输出文件,而是一个简单的文本输出文件。

下面的代码会产生你想要的输出

def readAndWriteFile(read_file_path,write_file_path):
    with open(read_file_path,"r") as fin:
        output = [", ".join(element.split(',')) for element in fin.readlines()]
    print("output:",output)
    
    with open(write_file_path,'w') as fout:
        fout.writelines(output)
于 2020-08-06T07:08:26.890 回答
0

这是一个简单的解决方法:

import csv

class CSV_Translater(object):
    """ Output file-like object that translates characters. """
    def __init__(self, f, old, new):
        self.f = f
        self.old = old
        self.new = new
    def write(self, s):
        self.f.write(s.replace(self.old, self.new))
    def close(self):
        self.f.close()
    def flush(self):
        self.f.flush()

my_new_row = ['6', 'abc6', 'xyz6']


with open('data.csv', "r+") as filehandle:
    reader = csv.reader(filehandle)
    with open('out_test.csv', "w") as opfile:
        translater = CSV_Translater(opfile, ',', ', ')
        writer = csv.writer(translater, delimiter=',')
        for row in reader:
            writer.writerow(row)
        writer.writerow(my_new_row)

示例文件输出截图1

于 2020-08-06T08:23:15.943 回答
-2

不是最好的解决方案,但根据您的要求,我能想到的一种解决方案是

import csv
my_new_row = [6, 'abc6', 'xyz6']
with open('data.csv', 'a') as filehandle:
    writer = csv.writer(filehandle, delimiter=',')
    writer.writerow([' ' + str(i) if isinstance(i, str) else i for i in my_new_row])

输出/输出: 6, abc6, xyz6

试试这个,让我知道这是否有帮助。

于 2020-08-06T06:37:45.080 回答