Home > Blockchain >  Python create filenames without parentheses and quotes
Python create filenames without parentheses and quotes

Time:01-27

So i am new to Python and found below script. I adjusted it in such a way that its creating files based on 2 values ; account_code and account. However, the files that are created are looking like ('account_code','account').csv / ('blablabla','123').csv.

I tried multiple things with strip etc but to no avail. How would i be able to remove parentheses / quotes from the file name?

import csv

with open(r"Outbox\file.csv") as fin:    
    csvin = csv.DictReader(fin)
    # Category -> open file lookup
    outputs = {}
    for row in csvin:
        cat = row['account_code'],row['account']
        # Open a new file and write the header
        if cat not in outputs:
            fout = open('{}.csv'.format(cat), 'w',newline='')
            dw = csv.DictWriter(fout, fieldnames=csvin.fieldnames)
            dw.writeheader()
            outputs[cat] = fout, dw
        # Always write the row
        outputs[cat][1].writerow(row)
    # Close all the files
    for fout, _ in outputs.values():
        fout.close()

CodePudding user response:

When you do cat = row['account_code'], row['account'], it is creating a tuple containing row['account_code'] and row['account'] (in this order), not a string (because it is not already a string). Then, in '{}.csv'.format(cat), cat will be transformed to a string using it's own string representation function (__repr__), which is ('account_code','account').

You should make cat become a string, then something like this would do the job.

cat = '{}_{}'.format(row['account_code'],row['account'])
  •  Tags:  
  • Related