Python:
I'm trying to compare file names in a directory after stripping some n characters from the name. If the file name exists after the strip, then it will add a number to the end of the name.
I created a code that renames all the file names in the directory, but I'm having trouble trying to do the comparison AND THEN renaming due to the existing same file name after the strip.
import os
def main():
i = 0
for filename in os.listdir("C:\\Users\User\Desktop\Tests"):
try:
dirName != filename
print (filename)
except dirName == filename:
dst ="dup" + str(i) + ".txt"
src = dirName
dst ='Test'+ dst
# rename() function will
# rename all the files
os.rename(src, dst)
i += 1
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
I get it to rename the files directly but unable to do the comparison with the file names THEN renaming if it is the same name. New to python!
def main():
i = 0
for root, dirs, files in os.walk("C:\\Users\User\Desktop\Tests"):
for filename in files:
for filename2 in files :
if filename != filename2: # if your file name is not repetitious you will pass it and compare next one
#print(filename)
continue
# if a repetitious filename found your code for rename it will come up
dst ="dup" + str(i) + ".txt"
src = filename
dst ='Test'+ dst
os.rename(src, dst)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.