所以我对 Python 相当陌生,我已经在网络和堆栈溢出中搜索了一个简单的解决方案。我确信我遇到过一个可行的解决方案。然而,我很难将其他人的解决方案应用到我需要的环境中。
我有一个模板文件,我已设法将其复制到“projStorage”变量的多个子目录中。
例如
+ proj\Storage\dir
+ Seq1
+ template.file >> which I want to rename to >> Seq1_stringHere.File
+ Seq2
+ template.file >> Seq2_stringHere.File
+ Seq3
+ template.file >> Seq3_stringHere.File
问题是我想根据模板文件刚刚复制到的目录重命名它们。为此,我正在执行 os.listdir(seqFileList),我希望它会返回每个模板文件的列表,以便我可以重命名为 Seq 目录名称 + 字符串格式。
我已经使用 for 循环完成了此操作。现在我明白我的“seqFileList”正在为 proj\Storage\Dir 中的每个文件夹执行 listdir() 并返回我的文件列表。 我已经看到了“展平列表”的解决方案,但我不太明白它是如何工作的。 打印 seqFileList 返回类似的内容,
['Template.file']
['Template.file']
['Template.file']
当我想要的是
['Template.file','Template.file','Template.file',]
这样我就可以重命名为
['Seq01_strHere.File','Seq02_strHere.File','Seq03_strHere.File',]
此外,我知道代码的重命名部分尚未实现,因为我不确定如何进行。我知道一个解决方案是 os.rename() 但我不确定在哪里正确实现它。
我知道这个问题可能并不新鲜,而且对某些人来说非常简单。我并不是想成为一个“帮助吸血鬼”,因为我真的想为自己内化这些东西。所以请原谅我的新鲜感。 任何和所有解决方案都值得赞赏。
为了清楚起见,我替换了文件路径和项目名称。
提前致谢。
import os, shutil
projTemplate = 'Path\\To\\Template.file'
projStorage = 'Proj\\Storage\\dir'
projSeqs = os.listdir(projStorage)
for seqs in projSeqs:
seqFileDir = os.path.join(projStorage, seqs)
shutil.copy2(projTemplate, seqFileDir)
seqFileList = os.listdir(seqFileDir)
print seqFileDir
最佳答案
为什么不在子文件夹中复制模板时重命名它?
for seqs in projSeqs:
seqFileDir = os.path.join(projStorage, seqs)
seqFileTemplate = os.path.join(seqFileDir, '%s_stringHere.File' % seqs)
shutil.copyfile(projTemplate, seqFileTemplate)
shutil.copystat(projTemplate, seqFileTemplate)
关于python - 将模板文件复制到多个目录,根据目录查询模板文件重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135405/