Python- Replace all spaces with underscores and convert to lowercase for all files in a directory

python

Solution

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

Problem

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()) ```

Original source

Related problems