从目录中读取所有文件

Nai*_*ive 4 python directory

以下代码是读取下载目录中的所有文件,但是当我执行此代码时,它不会打印(显示),此代码有什么问题..?

import glob   
path = '/home/mypc/download/*.html'   
files=glob.glob(path)   
for file in files:     
    f=open(file, 'r')  
    f.readlines()   
    f.close() 
Run Code Online (Sandbox Code Playgroud)

And*_*ini 8

readlines()文件对象的方法返回一个 Python 列表。它不会自动在标准输出上写入文件的内容:Python 是一种脚本语言,但不是 shell 脚本语言!

你应该更换:

f.readlines()
Run Code Online (Sandbox Code Playgroud)

和:

sys.stdout.write(f.read())
Run Code Online (Sandbox Code Playgroud)

请注意,我正在使用read()而不是readlines(). 正如我所说,readlines()返回一个列表,但在这里我们想打印一个字符串——并read()执行我们想要的操作:它读取整个文件并返回一个字符串。当文件很大时它不是最佳的(因为它会使用大量的内存),但它可以工作。

值得注意的是,您的代码有缺陷。你说:下面的代码是读取下载目录中的所有文件。您的代码实际上会尝试读取以.html. 如果您的代码找到以 结尾的目录.html,它将大声崩溃。

最后,您应该更喜欢with在打开文件时使用该语句,尤其是当您打开许多文件时。该with语句将确保文件在您完成工作后立即关闭,即使发生错误也是如此。

因此,您的代码应如下所示:

import sys
import glob
import errno

path = '/home/mypc/download/*.html'   
files = glob.glob(path)   
for name in files: # 'file' is a builtin type, 'name' is a less-ambiguous variable name.
    try:
        with open(name) as f: # No need to specify 'r': this is the default.
            sys.stdout.write(f.read())
    except IOError as exc:
        if exc.errno != errno.EISDIR: # Do not fail if a directory is found, just ignore it.
            raise # Propagate other kinds of IOError.
Run Code Online (Sandbox Code Playgroud)