python - 如何在 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) 具有我需要在代码后面的某些操作中使用的数值,所以这就是我需要“重命名”它们的原因。
解决方案
尝试使用 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)
推荐阅读
- c++ - 为什么在下面的 C 代码中,结构指针 **s 的大小在取消引用到 '*s' 并进一步到 's' 时是 8?. 谁能解释一下
- javascript - 将功能组件更改为类组件时,`npm init react-app` 导致 `'React' is not defined no-undef`
- android - 如何在android中为文件提供URI
- swift - 如何省略日期字符串(日、月、年)中的缺失字段?
- javascript - 我想刷新我的 html 页面上可用的所有 div,即按标签,我有 2 个代码如何 imerge
- django - Django ModelFormset 表单返回空数据
- python - 使用机器学习为特定用例优化 Pytesseract OCR 准确性?
- python - 如何重新加载文件并能够在不以python中的模块名称为前缀的情况下调用它?
- android - Flutter:应用启动后如何获取 NFC 消息
- architecture - 如何重构与许多其他类有依赖关系的大类?