【问题标题】:Python: How to read all files in a directoryPython:如何读取目录中的所有文件
【发布时间】:2014-11-02 03:59:52
【问题描述】:

我发现这段代码可以读取特定文件的所有行。

如何编辑它以使其读取目录“文件夹”中的所有文件(html,文本,php .etc),而无需指定每个文件的路径?我想在目录中的每个文件中搜索关键字。

 path = '/Users/folder/index.html'
    files = glob.glob(path)
    for name in files:  
        try:
            with open(name) as f:  
                sys.stdout.write(f.read())
        except IOError as exc:
            if exc.errno != errno.EISDIR:  
                raise 

【问题讨论】:

  • 如果那个关键字如果找到了你想做的事???
  • @Hackaholic 现在只是打印一些东西
  • 检查我给出的代码
  • @Hackaholic 我现在得到 No such file or directory: 'index.html'

标签: python python-2.7


【解决方案1】:
import os
your_path = 'some_path'
files = os.listdir(your_path)
keyword = 'your_keyword'
for file in files:
    if os.path.isfile(os.path.join(your_path, file)):
        f = open(os.path.join(your_path, file),'r')
        for x in f:
            if keyword in x:
                #do what you want
        f.close()

os.listdir('your_path') 将列出目录的所有内容
os.path.isfile 将检查其文件与否

【讨论】:

  • 编辑后的代码没有任何输出,除了 Process finished with exit code 0
  • 假设您使用自己的代码更改“#do what you want”行,该代码将执行您想要的操作,包括打印任何输出。
  • 这段代码不完整,它并没有真正起作用,因此不能满足这个问题的目的。将if os.path.isfile(file): 更改为if os.path.isfile(os.path.join(your_path,file)):。然后它将打开文件。
  • 如果您在读取文件时遇到编码问题,请添加f=open(your_path_file,'r', encoding = "ISO-8859-1")
【解决方案2】:

更新 Python 3.4+

读取所有文件

from pathlib import Path

for child in Path('.').iterdir():
    if child.is_file():
        print(f"{child.name}:\n{child.read_text()}\n")

读取所有按扩展名过滤的文件

from pathlib import Path

for p in Path('.').glob('*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

读取目录树中按扩展名过滤的所有文件

from pathlib import Path

for p in Path('.').glob('**/*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

或者等效地,使用Path.rglob(pattern):

from pathlib import Path

for p in Path('.').rglob('*.txt'):
    print(f"{p.name}:\n{p.read_text()}\n")

Path.open()

作为Path.read_text()[或Path.read_bytes()用于二进制文件]的替代品,还有Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None),类似于Python内置函数open()

from pathlib import Path

for p in Path('.').glob('*.txt'):
    with p.open() as f:
        print(f"{p.name}:\n{f.read()}\n")

【讨论】:

  • 感谢更新。对遇到此问题的其他人很有用
猜你喜欢
  • 2014-11-10
  • 2019-09-28
  • 1970-01-01
  • 2013-12-02
  • 2019-11-13
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
相关资源
最近更新 更多