假设我有一条路径A.
A = / Users / myname / Documents / folder1
在folder1中,有folder2和folder3,在folder2和folder3中,有一些名为“file.txt”的文件。我想浏览folder1中的每个子目录,并将“file.txt”替换为“folder [#] _ file.txt”(子目录的名称+“file.txt”)。
我有以下代码:
import os, sys
def main():
path = "/Users/myname/Documents/folder1/"
for root, subdirs, files in os.walk(path):
root = root + "/"
parent_directory = os.path.dirname(root)
for filename in os.listdir(parent_directory):
if filename.endswith("file.txt"):
path = os.path.join(parent_directory, filename)
target = os.path.join(root, parent_directory + "_" + filename) //I know this is where the issue is...not sure what to do.
os.rename(path, target)
if __name__ == '__main__':
main()
然而,使用print语句,我看到路径设置为:
/Users/myname/Documents/folder1/folder2/file.txt
和目标设置为:
/Users/myname/Documents/folder1/folder2_file.txt
而不是
/Users/myname/Documents/folder1/folder2/folder2_file.txt
我该如何解决这个问题?我已经在我的代码中找到了错误的行,我知道它为什么会这样做,但我不确定如何调整它。
答案 0 :(得分:0)
您可以使用os.path.basename
从路径字符串中获取最后一个目录。然后,您可以在其前面添加文件名。因此,将您设置的行target
切换为以下内容:
target = os.path.join(path, root + os.path.basename(parent_directory) + "_" + filename)