在python中的文件夹中循环并打开文件会引发错误

在python中的文件夹中循环并打开文件会引发错误,第1张

在python中的文件夹中循环并打开文件会引发错误

os.listdir()
提供文件名,但不提供文件路径:

import osfor filename in os.listdir('path/to/dir'):    if filename.endswith('.log'):        with open(os.path.join('path/to/dir', filename)) as f: content = f.read()

或者,您可以使用该

glob
模块。该
glob.glob()
功能允许您使用模式过滤文件:

import osimport globfor filepath in glob.glob(os.path.join('path/to/dir', '*.log')):    with open(filepath) as f:        content = f.read()


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5664531.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存