【发布时间】:2021-06-13 01:07:16
【问题描述】:
我有以下文件夹结构
folder1/
file1a.txt
file1b.txt
file1c.txt
file2a.txt
file2b.txt
file2c.txt
file3a.txt
file3b.txt
file3c.txt
file4a.txt
file4b.txt
file4c.txt
file5a.txt
file5b.txt
file5c.txt
folder2/
file1a.txt
file1b.txt
file1c.txt
file2a.txt
file2b.txt
file2c.txt
file3a.txt
file3b.txt
file3c.txt
file4a.txt
file4b.txt
file4c.txt
file5a.txt
file5b.txt
file5c.txt
我想重命名folder2 中的文件,使它们与folder1 中的文件按顺序排列——即
folder2/
file6a.txt
file6b.txt
file6c.txt
file7a.txt
file7b.txt
file7c.txt
file8a.txt
file8b.txt
file8c.txt
file9a.txt
file9b.txt
file9c.txt
file10a.txt
file10b.txt
file10c.txt
我的策略是(伪代码):
1. read in files from folder1
2. make a unique list of those files
3. count the number of files in that unique list
4. set that number to be the starting number for the files to be renamed in folder2 (e.g. 6)
5. count the number of files in folder2 and set that to be the end of the range (e.g. 10)
6. and rename the files in folder2 as shown in the example
我无法想象的步骤是重复文件夹 2 中的文件名——即file6a.txt, file6b.txt, file6c.txt。
在 BASH 中我可以运行这个:
i=1; j=6; rename file${i} file${j} folder2/file${i}*
pythonic 的做法是什么?
编辑:将问题更新为更准确,并添加伪代码来说明策略。
【问题讨论】:
-
将文件列表读入单个列表,对其进行排序,使用
enumerate()跟踪列表中的索引,并使用该枚举索引重命名以folder2/开头的文件。跨度> -
你能展示一下你到目前为止所尝试的吗?
-
您好,我只成功读取并统计了文件夹 1 中的文件。
-
“告诉我如何解决这个编码问题”是off-topic for Stack Overflow。您应该发送honest attempt at the solution,然后然后询问有关它的具体问题(如有必要)。
-
文件目录(文件夹)中不能有两个同名的文件,因此它们的名称在它们的任何列表中都是唯一的(这意味着您的问题中显示的示例文件夹结构是不可能的) .