在单个文件夹中读取多个.txt文件

时间:2016-12-06 18:09:18

标签: python list text glob

我想从单个文件夹中的多个.txt文件中读取,并将每行读作列表。

example name of the files

example content of each file

这是我的代码,但它什么都不打印。

import glob
import errno
path = '/Users/xccxken/PycharmProjects/untitled7/NNRelease/*.txt'
files = glob.glob(path)
for name in files:
    try:
        with open(name) as f:
            for line in f:
                words = list()
                for word in line.split():
                    words.append(word)
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise
    print(words)

我希望结果是两个列表a和b

a=[class,company,family,..]
b=[size, size, size,...]

另一个问题是打印列表包含一些空列表,(我认为这是因为原始的txt文件有空行)请告诉我如何删除这些空列表。谢谢!

此外,我需要删除包含"#“谢谢!

的列表

1 个答案:

答案 0 :(得分:1)

我认为files可能是空的。在目录

中使用绝对路径或os.chdir
import glob
import errno
path = 'C:/Users/xccxken/PycharmProjects/untitled7/NNRelease/*.txt' #note C:
files = glob.glob(path)
for name in files:
    try:
        with open(name) as f:
            for line in f:
                print(line.split())
    except IOError as exc: #Not sure what error this is
        if exc.errno != errno.EISDIR:
            raise

仅打印带数据的行

    with open(name) as f:
        for line in f:
            split = line.split()
            if split:
                print(line.split())