繁体   English   中英

Python:有没有办法在脚本用完之前系统地打开脚本中的文件?

[英]Python: Is there a way to systematically open files in a script until a directory has been exhausted?

我想用Python编写一个脚本,该脚本将系统地打开文件,但是我不确定这种情况如何发生。 本质上,我想要这样的东西:

with open(file1) as thefile:
    #do stuff

with open(file2) as the file:
   #do the same thing as before

.... #does this until the directory is exhausted

有很多文件需要处理,因此我正在寻找一堆with命令中的硬编码替代方法。 有没有办法在循环中执行此操作,以识别出它已耗尽目录中的所有文件?

是的,有很多方法。 一种方法是遍历glob.glob()的结果:

#UNTESTED
import glob
for filename in glob.glob('*'):
    with open(filename) as the_file:
        # do the thing

如果只想对具有特定命名模式的文件进行操作,则可以使用例如: glob.glob('ABC*.txt')

Python os软件包具有许多用于操作系统的出色工具,尤其是文件和进程管理。

import os

for f in os.listdir("."):
    with open(f) as the_file:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM