2

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!

1 Answer 1

2

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')))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply! I get the following error when I try that: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'E:/CSVFILES/20180808\\ismRawTec_G10_20180808.csv' -> 'E:/CSVFILES/2018_08_08\\ismRawTec_G10_2018_08_08.csv'
That's because your files in are in a directory called 20180808, so your replace method tries to replace both, and write files to a directory that doesn't exist. You can fix this with the basename function - see my edit above.
Hi @Julian if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.