如何从Python的单个文件夹中读取多个txt文件?

问题描述:

如何从Python的单个文件夹中读取多个txt文件?

How can I read multiple txt file from a single folder in Python?

我尝试使用以下代码,但无法正常工作.

I tried with the following code but it is not working.

import glob

import errno

path = '/home/student/Desktop/thesis/ndtvnews/garbage'

files = glob.glob(path)

for name in files:
    try:
        with open(name) as f:
            print name

        for line in f:
            print line,

        f.close()

    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

您的问题不正确.您应该在路径末尾添加/* 以选择路径中的所有文件(或目录),然后检查它们是否是带有 os.path.isfile 的文件>.像这样:

Your glob isn't correct. You should add a /* to the end of your path to select all files (or directories) in your path, and then check if they are files with os.path.isfile. Something like:

from os.path import isfile
files=filter(isfile,glob.glob('%s/*'%path))

您还对实际营业额有疑问.当您的 with 语句结束时,文件将关闭,并且 f 不再可用.您对该文件所做的任何操作都应在 with 语句下.而且您不应该明确关闭它.

You also have an issue with the actual opening. When your with statement ends, the file is closed and f is no longer accessible. Anything you do with the file should be under the with statement. And you shouldn't explicitly close it.