I am trying to do as the title explains, but am given the message WinError2: cannot find the file specified 'New Text Document.txt' -> 'new_text_document.txt' with the code snippet below. Yes, my Desktop is on drive letter D, and this assumes the target directory is named 'directory'. I have a sample file in the directory named 'New Text Document.txt'. I just can't figure out where the problem is.
import os
path = 'D:\Desktop\directory'
filenames = os.listdir(path)
for filename in filenames:
os.rename(filename, filename.replace(' ', '_').lower())
A one-liner using list comprehension:
import os
directory = 'D:\Desktop\directory'
[os.rename(os.path.join(directory, f), os.path.join(directory, f).replace(' ', '_').lower()) for f in os.listdir(directory)]
list-comprehension borrowed from answer Batch Renaming of Files in a Directory
use the full file naming for safer os operations:
import os
path = 'D:\\test'
for filename in os.listdir(path):
#print(filename)
os.rename(os.path.join(path,filename),os.path.join(path, filename.replace(' ', '_').lower()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With