ATP
ATP

Reputation: 643

How to change several files names in a specific folder on Python?

so I've been using the following code to change the file name of all of the files in a specific folder.

import os
[os.rename(f,f.replace('20180810','2018_08_10')) for f in os.listdir()]

The issue I'm having is that whenever I use this code, I have to save a copy of it and paste it in the folder where the files are present. I'd like to be able to have a general code where I can specify the path without having to be in that folder. I tried the following but for some reason it says it can't find the file:

path = 'E:/CSVFILES/20180808/'
[os.rename(f,f.replace('20180810','2018_08_10')) for f in os.listdir(path)]

If I run os.listdir(path), it runs fine and it displays the files in the folder, so I'm not sure why it's not working.

Thanks!

Upvotes: 2

Views: 171

Answers (1)

Tim
Tim

Reputation: 2843

os.listdir lists all the files in the directory, but without the full path, and os.replace requires a full path if the file isn't in the working directory. Instead, use iglob, which returns full paths:

>>> from glob import iglob
>>> path = 'E:/CSVFILES/20180808/*'
>>> for f in iglob(path):
>>>     os.rename(f, f.replace('20180810','2018_08_10'))

Edit: Because your files are in a location that contains the same text that you're trying to replace, you can use basename and join to only replace the text in the filename:

>>> from glob import iglob
>>> from os.path import basename, join
>>> path = 'E:/CSVFILES/20180808'
>>> for f in iglob(join(path, "*")):
>>>     os.rename(f, join(path, basename(f).replace('20180810','2018_08_10')))

Upvotes: 2

Related Questions