Note that there are some explanatory texts on larger screens.

plurals
  1. POFile renaming; Can I get some feedback
    text
    copied!<p>Background: A friend of mine, who just might have some OCD issues, was telling me a story of how he was not looking forward to the hours of work he was about to invest into renaming tons of song files that had the words An, The, Of and many more capitalized.</p> <p>Criteria: He gave me a list of words, omitted here because you will see them in the code, and told me that capitalization is O.K. if they are at the beginning of the song, but otherwise they must be lowercase.</p> <p>Question 1: This is actually my first script and I am looking for some feedback. If there is a better way to write this, I would like to see it so I can improve my coding. The script is functional and does exactly what I would like it to do.</p> <p>Question 2: Initially I did not have all 3 functions. I only had the function that replaced words. For some reason it would not work on files that looked like this "The Dark Side Of The Moon". When I ran the code, the "Of" would be replaced but neither of the "The"s would be. So, through trial and error I found that if I lowercase the first letter of the file, do my replace function and finally uppercase the file, it would work. Any clue as to why?</p> <pre><code>import os words = ['A','An','The','Of','For','To','By','Or','Is','In','Out','If','Oh','And','On','At'] fileList = [] rootdir = '' #Where are the files? Is the input a valid directory? while True: rootdir = raw_input('Where is your itunes library? ') if os.path.isdir(rootdir): break print('That is not a valid directory. Try again.') #Get a list of all the files in the directory/sub-directory's for root, subFolders, files in os.walk(rootdir): for file in files: fileList.append(os.path.join(root)) #Create a function that replaces words. def rename(a,b,c): for file in os.listdir(c): if file.find(a): os.rename(file,file.replace(a,b)) #Create a function that changes the first letter in a filename to lowercase. def renameL(): for file in os.listdir(os.getcwd()): if file.find(' '): os.rename(file,file.replace(file,file[0].lower()+file[1:])) #Creat a function that changes the first letter in a filename to uppercase. def renameU(): for file in os.listdir(os.getcwd()): if file.find(' '): os.rename(file,file.replace(file,file[0].upper()+file[1:])) #Change directory/lowercase the first letter of the filename/replace the offending word/uppercase the first letter of the filename. for x in fileList: for y in words: os.chdir(x) renameL() rename(y,y.lower(),x) renameU() Exit = raw_input('Press enter to exit.') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload