小编CHb*_*ler的帖子

打开从 os.listdir() 找到的文件并对文件执行任务

所以我想打开一个目录中的每个文件(这个目录中有4个纯文本文档)。并执行诸如查找特定单词及其在每个文件中出现的次数之类的操作。

这是我使用的代码,但是我得到了没有这样的文件或目录的错误,但是我在打印路径时,它清楚地显示了每个文件的名称。

import re
import os

path = 'C:\\Python27\\projects\\Alabama\\New folder'

pattern = re.compile(r"\bmay not\b",re.IGNORECASE)
pattern1 = re.compile(r"\bshall\b",re.IGNORECASE)
pattern2 = re.compile(r"\bmust\b",re.IGNORECASE)
pattern3 = re.compile(r"\bprohibited\b",re.IGNORECASE)
pattern4 = re.compile(r"\brequired\b",re.IGNORECASE)

for filenames in os.listdir(path):
 with open(filenames) as myfile:
    total = 0
    total1 = 0
    total2 = 0
    total3 = 0
    total4 = 0
    for line in myfile:
        m = re.findall(pattern, line)
        m1 = re.findall(pattern1, line)
        m2 = re.findall(pattern2, line)
        m3 = re.findall(pattern3, line)
        m4 = re.findall(pattern4, line)
        total += len(m)
        total1 += len(m1)
        total2 …
Run Code Online (Sandbox Code Playgroud)

python directory file pipe python-2.7

1
推荐指数
1
解决办法
8569
查看次数

标签 统计

directory ×1

file ×1

pipe ×1

python ×1

python-2.7 ×1