Reputation: 103
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())
Upvotes: 10
Views: 15626
Reputation: 858
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()))
Upvotes: 8
Reputation: 5568
Alternative method using os.walk(directory) if you want to do this recursively through several levels of folders:
import os
directory = r'D:\Desktop\directory'
# Use underscore? Otherwise defaults to hyphen
is_use_underscore = True
char_to_use = '_' if is_use_underscore else '-'
print("Renaming files now!")
for root, dirs, files in os.walk(directory):
print(f"root: {root}")
print(f"dirs: {dirs}")
print(f"files: {files}")
for current_filename in files:
new_filename = current_filename.replace(' ', char_to_use)
print(f"current filename: {current_filename}")
print(f" new filename: {new_filename}")
os.rename(
os.path.join(root, current_filename),
os.path.join(root, new_filename)
)
print("All done!")
Upvotes: 2
Reputation: 8047
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
Upvotes: 13
Reputation: 144
Because you did not specify the directory where the New Text Document.txt is for the os.rename function. You can just add this line before the for loop.
os.chdir(path)
And either use raw strings or full file paths, because the way you defined path will also give you an error.
path = r'D:\Desktop\directory
' or path = 'D:\\Desktop\\directory'
Upvotes: 0