HiThere HiThere - 9 months ago 51
Python Question

How to loop over directories and rename files?

Im ney to python and therefore apologize for the triviality of my question:

I have the following file structure, where a

file with employee is saved on daily basis:


I would like to go through each file and rename it. Afterwards I would like to save the new files in one common directory
. What I tried:

import sys
import os

path = 'dir/'

for folderName, subfolders, filenames in os.walk(path):
for filename in filenames:
infilename = os.path.join(path, filename)
newname = infilename.replace('.csv.bz2', '.csv')
output = os.rename(infilename, newname)

But I get the error:

output = os.rename(infilename, newname)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'dir/employee.csv.bz2' -> 'dir/employee.csv'

Not sure what Im doing wrong.

Answer Source

Use folderName instead of path in os.path.join(path, filename) because folderName has full path to subfolder.

infilename = os.path.join(folderName, filename)

If you want to save in one folder then use this folder in newname and rename() will move file to new place.

newname = os.path.join('dir', 'common', filename.replace('.csv.bz2', '.csv'))

BTW: But you have to create this folder first.


or to create folder and all intermediate folders from path