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

问题描述:

我想从单个文件夹中的多个.txt文件中读取文件,并以列表的形式读取每一行.

I want to read from multiple .txt file in a single folder, and read every line as a list.

这是我的代码,但是什么也不打印.

This is my code, however it prints nothing.

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

I hope the resulting is two lists a and b

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

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

Another question is the print lists contains some empty lists, (I think it is because the original txt files has empty row) Please tell me how to remove these empty lists. Thanks!

此外,我需要删除包含#"谢谢的列表!

In addition, I need to delete the lists that contain "#" thanks!

我认为files可能为空.使用绝对路径或os.chdir进入目录

I think files may be empty. Use an absolute path, or os.chdir into the directory

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())