首页 > 解决方案 > 如何在 python 上读取具有相似名称的文件然后使用它们?

问题描述

所以我在一个项目中工作,我需要读取一堆文件,除了一个数字,它们具有相同的名称,例如:

thing1.txt
thing2.txt
thing3.txt

然后我必须与他们合作,给他们取另一个名字:

example1='.\path\thing1.txt'

有什么方法可以让代码读取我这些区分数字的文件,然后以编号的形式将它们分配给新名称?

import fnmatch

for filename in os.listdir('.'):
    if fnmatch.fnmatch(filename, 'thing*.txt'):
        print(filename)

使用我现在使用的代码,我可以读取具有相同名称和不同编号的文件,但我无法在循环中重命名它们以在之后使用它们。

我想要一个类似循环的东西:

example*=thing*

其中 * 应该是数字。

编辑:我应该这么说,但是我使用的文件 (thing1/2/3) 具有我需要在代码后面的某些操作中使用的数值,所以这就是我需要“重命名”它们的原因。

标签: pythonpython-3.xtext

解决方案


尝试使用 os.walk()。os.walk

for (root,dirs,files) in os.walk(main_folder): 
#iterate over all the files in the folders and sub folders
    for file in files:
         filepath = os.path.join(root,file)
         # read the file from thing and write the file in example
         with open(filepath ) as f:
              with open(filepath.replace('thing',example),'w') as g:
                      g.write(f)

推荐阅读