简体   繁体   English

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

[英]Python : set delimiter as both comma and space ', '

I want to append my CSV file with a new row But the new row must be separated by a comma as well as space between them.我想 append 我的 CSV 文件有一个新行但是新行必须用逗号分隔,并且它们之间有空格。 I can only separate them with either comma or space.我只能用逗号或空格分隔它们。

The current file is:当前文件是:

data.csv数据.csv

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

I want it as:我希望它为:

data.csv数据.csv

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

My code for writing CSV:我编写 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)

The format you want to print is seem like not a stander CSV format.您要打印的格式似乎不是标准的 CSV 格式。 So you can write your own writer to print that string format.因此,您可以编写自己的编写器来打印该字符串格式。

Common Format and MIME Type for Comma-Separated Values (CSV) Files逗号分隔值 (CSV) 文件的通用格式和 MIME 类型

This certainly isn't very efficient but it does solve your problem, with only the new row containing spaces after the delimiter.这当然不是很有效,但它确实解决了您的问题,只有新行在分隔符后包含空格。

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)

The output is all written to the new_file.csv output 全部写入new_file.csv

AS CVS file format means "," comma-separated value, I am assuming now you no longer required CSV output file but rather a simple text output file. AS CVS 文件格式表示“,”逗号分隔值,我假设您现在不再需要 CSV output 文件,而是一个简单的文本 output 文件。

Below code would produce your desired output下面的代码将产生您想要的 output

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)

Here is a simple workaround:这是一个简单的解决方法:

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 1

Not the best solution, but based on your requirement, one solution that I can think off is不是最好的解决方案,但根据您的要求,我能想到的一种解决方案是

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 O/P: 6, abc6, xyz6

Try this and let me know if this help.试试这个,让我知道这是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM