I am currently trying to learn python by writing a script that will clean up my downloads folder by preserving the name of the object while removing special characters and extra data from the folder/file name.
ie:
../Completed Downloads/random.download.here.x264.team
../Completed Download/random download here
as well as
file.name.randomstring_randomstring.mkv
file name randomstring randomstring (date).mkv
I've been searching for a while now, but while I can make a script that sees these files - I can't seem to get it to just pluck out each individual special character and rename it. When I do, I get:
Traceback (most recent call last):
File "C:\Python27\Scripts\plexprep.py", line 7, in <module>
os.rename(dir, dir.replace(".", "").lower())
WindowsError: [Error 2] The system cannot find the file specified
here is the start of my script:
import fnmatch
import os
#Matches directories for Plex and renames directories to help Plex crawl.
for dir in os.listdir('F:\Downloads\Completed Downloads'):
if fnmatch.fnmatch(dir, '*'):
os.rename(dir, dir.replace(".", "").lower())
#Matches filenames for Plex and renames files/subdirectories to help Plex crawl.
As @cricket_007 said in the comment, you should escape backslashes by adding r
in front of the path:
for dir in os.listdir(r'F:\Downloads\Completed Downloads'):
However the WindowsError
is caused by the something else: In your loop, dir
will only be the name of the subfolder, but not the complete path to it. A possible solution would be:
base = r'F:\Downloads\Completed Downloads'
for dir in os.listdir(base):
path = os.path.join(base, dir)
# Now use your os.rename() logic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.