Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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())
like image 296
Gl0rph Avatar asked May 02 '17 00:05

Gl0rph


2 Answers

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

like image 110
chickity china chinese chicken Avatar answered Sep 19 '22 01:09

chickity china chinese chicken


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())) 
like image 37
lsalamon Avatar answered Sep 20 '22 01:09

lsalamon