Python : 将分隔符设置为逗号和 space ', '

Python : set delimiter as both comma and space ', '

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

分隔它们

当前文件是:

data.csv

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

我想要它:

data.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)

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

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])

O/P: 6, abc6, xyz6

试试这个,如果有帮助请告诉我。

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

Common Format and MIME Type for Comma-Separated Values (CSV) Files

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

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

AS CVS 文件格式表示“,”comma-separated 值,我假设您现在不再需要 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)

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

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