我是 python 和编码的新手,作为第一个项目,我希望创建一个 python 脚本,它将遍历文件夹结构并查看每个子文件夹内部并重命名其中的文件以匹配子文件夹的名称。
\n\n文件夹结构示例:
\n\nroot folder\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 first sub-folder (Batman)\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 filename.extension (joker.pdf)\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 filename.differentExtension (bane.jpg)\n\xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 second sub-folder\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 filename.extension\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 filename.differentExtension\nRun Code Online (Sandbox Code Playgroud)\n\n因此,脚本完成后,结果将如下所示:
\n\nroot folder\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 first sub-folder (Batman)\n\xe2\x94\x82 \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 filename.extension (Batman.pdf)\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 filename.differentExtension (Batman.jpg)\n\xe2\x94\x82\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 second sub-folder\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 filename.extension\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 filename.differentExtension\nRun Code Online (Sandbox Code Playgroud)\n\n我正在寻找有关如何解决此问题的建议,我正在考虑使用 os.path.splitext 将文件名与文件扩展名分开,但我不确定如何将文件名更改为子文件夹值,然后连接文件名和文件扩展名重新组合在一起。
\n我将使用os.walk, 并ntpath使用递归函数来遍历所有目录和子目录...随时重命名。下面的代码绝对可以被压缩......但我想让它更明确,以帮助您理解正在发生的事情。
import os
import ntpath
print(os.getcwd()) # Information for testing
rootDir = "/home/user/eclipse-workspace/test" # Will start here
# Create a recursive function.
# This function will call itself, to pass in new directories it finds
def walkit(rootDir):
# os.walk gives you the name of the directory it's in,
# all the subdirs (as a list),
# and all the filesnames (as a list)
for thisDir, thisDir_subDirs, thisDir_files in os.walk(rootDir):
print("---------------------------")
print("This Directory =", thisDir, "\nSubdirectories:", thisDir_subDirs, "\nFiles:", thisDir_files)
# Loop through and change the filenames first
for filename in thisDir_files:
# Get JUST the filename with extension
basename = ntpath.basename(filename)
# Split the filename into name + extension
name, ext = os.path.splitext(basename)
# Next split the last directory off the full directory path.
# Returns a tuple, so you have to take the second element "[1]"
newname = ntpath.split(thisDir)[1]
# Python join to create a new name + extension
newfilename = ''.join([newname, ext])
# Set the source by joining the current FULL directory path and the FULL old name
src = os.path.join(thisDir, filename)
# Set the destination by joining the current FULL path plus the FULL NEW name
dst = os.path.join(thisDir, newfilename)
try: # Use try except to catch problems
print("Renaming '{}' to '{}' ... ".format(src, dst), end = '')
os.rename(src, dst) # Rename the file
print("OK") # Worked
except Exception as e: # Failed
print("FAILED! (ERROR:{})".format(str(e)))
# Now cycle through the list of subdirectories and
# send each directory back into the walkit function.
# As each loop calls the function, it winds itself a new level deep
# Each time the function finishes, it "UNwinds" itself one level
for rootDir in thisDir_subDirs:
walkit(rootDir)
# Start the first iteratin by calling the function with the first directory to be parsed
walkit(rootDir)
Run Code Online (Sandbox Code Playgroud)
输出:
/home/user/eclipse-workspace/
---------------------------
This Directory = /home/user/eclipse-workspace/test
Subdirectories: ['robin', 'batman']
Files: []
---------------------------
This Directory = /home/user/eclipse-workspace/test/robin
Subdirectories: []
Files: ['riddler.jpg', 'penguin.pdf']
ext= .jpg
newfilename = robin.jpg
Renaming '/home/user/eclipse-workspace/test/robin/riddler.jpg' to '/home/user/eclipse-workspace/test/robin/robin.jpg' ... OK
ext= .pdf
newfilename = robin.pdf
Renaming '/home/user/eclipse-workspace/test/robin/penguin.pdf' to '/home/user/eclipse-workspace/test/robin/robin.pdf' ... OK
---------------------------
This Directory = /home/user/eclipse-workspace/test/batman
Subdirectories: []
Files: ['joker.pdf', 'bane.jpg']
ext= .pdf
newfilename = batman.pdf
Renaming '/home/user/eclipse-workspace/test/batman/joker.pdf' to '/home/user/eclipse-workspace/test/batman/batman.pdf' ... OK
ext= .jpg
newfilename = batman.jpg
Renaming '/home/user/eclipse-workspace/test/batman/bane.jpg' to '/home/user/eclipse-workspace/test/batman/batman.jpg' ... OK
Run Code Online (Sandbox Code Playgroud)