Home > database >  Insert comma after numbers
Insert comma after numbers

Time:02-02

In this code I'm trying to read multiple files in a folder, and insert a comma after each number. In the first file it works well, but in the second file there are two commas inserted after each number, something like this:

56,, 
74,,
2,,

How can I insert just one comma?

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

CodePudding user response:

This is happening because you're not inserting a comma after the number, you're inserting a comma after every line. You'll want to check if there's a comma at the end of the line is a comma doing something like this

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

If the function returns true, don't append a comma, if it returns false, then append a comma at the end of the line

  •  Tags:  
  • Related