在数字后插入逗号

Insert comma after numbers

在这段代码中,我试图读取一个文件夹中的多个文件,并在每个数字后插入一个逗号。 在第一个文件中效果很好,但在第二个文件中每个数字后插入了两个逗号,如下所示:

56,, 
74,,
2,,

如何只插入一个逗号?

input_path = Path(Path.home(), "Desktop", "m")
for root, dirs, files in os.walk(input_path):
    for file in files:
        file_path = Path(root, file)
        
        with open(file_path) as f:
            lines = f.read().splitlines()
        with open('C:/--/{}.txt'.format(file), "w") as f:
            for line in lines:
                f.write(line + ",\n")

发生这种情况是因为您没有在数字后插入逗号,而是在每一行后插入逗号。你会想检查行尾的逗号是否是逗号做这样的事情

def endsInComma(line):
    return line.endswith(',')

如果函数 returns 为真,则不附加逗号,如果 returns 为假,则在行尾附加逗号