Create csv file have the same name of reading file

Viewed 333

I am reading multiple csv files in folder, the reading file have names something like this m1,m2,m3,... so I need to create csv file (I am putting the new file in other path) have the same name of reading file how can do that? for example if first read file have name(m1), the create new file must have name(m1)

fpath = '/path/*' 
for file in iglob(fpath):
    with open(file) as f:
        for i in f:
            try:
               #some processing            
            except ValueError:
                pass
    with open('C:\\write\\ .csv','w') as ff:   
        ff.write()
2 Answers

When you loop over the file paths, just see if you get the full file name.

I am assuming you should get something like : "/path/m1.csv"

so you can get the filename in the following way:

filename = file.split("/")[-1].split(".")[0]

Once you have the filename, when you are writing the file, just do the following:

with open('C:\\write\\{}.csv'.format(filename),'w') as FF:   
    ff.write()

You can use this:

import os
from glob import iglob

source = '/path/*' 
for path in iglob(source):
    destfilepath = os.path.join('C:/write', os.path.basename(path).replace(".txt", ".csv"))
    with open(path, "r") as f1, open(destfilepath, 'w') as f2:
        for line in f1:
            try:
            # some processing on line
                pass
            except ValueError:
                pass

            f2.write(line) # --> write the processed line to output file
Related