HiThere HiThere - 19 days ago 8
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

.csv
file with employee is saved on daily basis:

dir/2012-01-01/employee.csv.bz2
dir/2012-01-02/employee.csv.bz2
dir/2012-01-03/employee.csv.bz2
dir/2012-01-04/employee.csv.bz2
dir/2012-01-05/employee.csv.bz2


I would like to go through each file and rename it. Afterwards I would like to save the new files in one common directory
dir/common
. 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

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.

os.mkdir('dir/common')

or to create folder and all intermediate folders from path

os.makedirs('dir/common/many/sub/folders/to/create')
Comments