在单个文件夹中读取多个.txt文件 [英] Read multiple .txt files in a single folder

查看:122
本文介绍了在单个文件夹中读取多个.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())

这篇关于在单个文件夹中读取多个.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆