Reputation: 1591
Ive successfully made a script which changes all $ to # in a directory, but it doesnt affect the foldername. So the foldername still remains the same name. How can I modify this to change the $ to # in the foldername as well?
def cleanFiles(self):
directoryChosen = self.directoryChoice()
print directoryChosen + " you made it to files selected"
#for file_names in os.listdir(directoryChosen):
#self.listWidget.addItem(file_names)
for n in os.listdir(directoryChosen):
print n + " made it here"
self.listWidget.addItem(n)
if os.path.isdir(directoryChosen):
print directoryChosen + " almost there"
newname = n.replace('$', '#')
print newname + " this is newname"
if newname != n:
print newname
print n
path = os.path.join(directoryChosen + '/' + n)
print path
target = os.path.join(directoryChosen + '/' + newname)
print target
os.rename(path, target)
Upvotes: 1
Views: 132
Reputation: 26578
The first problem you have is that you are doing this:
if os.path.isdir(directoryChosen):
When you want to do this:
if os.path.isdir(n):
So, with that in mind, inside your loop you actually want to reference n
, which are the folders and files you are trying to check.
The second problem that you have is in your usage of os.path.join
.
You don't have to join the way you are joining. You don't need to add the slash between the two, the join does that for you. I suggest reading the doc on that. So you want this:
path = os.path.join(directoryChosen, n)
target = os.path.join(directoryChosen, newname)
So, the code will then end up looking something like this:
for n in os.listdir(directoryChosen):
print n + " made it here"
self.listWidget.addItem(n)
if os.path.isdir(n):
print directoryChosen + " almost there"
newname = n.replace('$', '#')
print newname + " this is newname"
if newname != n:
print newname
print n
path = os.path.join(directoryChosen, n)
print path
target = os.path.join(directoryChosen, newname)
print target
os.rename(path, target)
Upvotes: 1
Reputation: 446
I am not sure if I understand your problem correctly. But, you can use the code below:
import os
def cleanFiles():
directoryChosen = "C:\\Test$234"
if os.path.isdir(directoryChosen):
for n in os.listdir(directoryChosen):
newname = n.replace('$', '#')
if newname != n:
path = os.path.join(directoryChosen + '/' + n)
target = os.path.join(directoryChosen + '/' + newname)
os.rename(path, target)
os.rename(directoryChosen, directoryChosen.replace('$','#'))
It renames your chosen directory as well, if that is what you are looking for.
Upvotes: 1
Reputation: 5558
if os.path.isdir(directoryChosen):
for n in os.listdir(directoryChosen):
self.listWidget.addItem(n)
newname = n.replace('$', '#')
if newname != n:
path = os.path.join(directoryChosen, n)
target = os.path.join(directoryChosen, newname)
os.rename(path, target)
newdir = directoryChosen.replace('$', '#')
if directoryChosen != newdir
os.rename(directoryChosen, newdir)
Upvotes: 1