读取多个txt文件python

时间:2020-02-28 22:12:12

标签: python string pandas

我有6000个txt文件可在python中读取。我正在尝试读取,但所有txt文件都是逐行显示的。

Subject: key dates and impact of upcoming sap implementation over the next few weeks , project apollo and beyond will conduct its final sap implementation ) this implementation will impact approximately 12 , 000 new users plus all existing system users . sap brings a new dynamic to enron , enhancing the timely flow and sharing of specific project , human resources , procurement , and financial information across business units and across continents . this final implementation will retire multiple , disparate systems and replace them with a common , integrated system encompassing many processes including payroll , timekeeping ...

因此,当我一一读取文件时,python将其分成几行(我知道那是ridiculos)。最后,将1封邮件分成多行。我尝试了read_csv所有的txt文件,但是python给出了ValueError: stat: path too long for Windows的错误。我不知道从现在开始该怎么办。

我尝试过:

import glob
import errno
path =r'C:\Users\frknk\OneDrive\Masaüstü\enron6\emails\*.txt'
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:
        if exc.errno != errno.EISDIR:
            raise

['Subject:', 'key', 'dates', 'and', 'impact', 'of', 'upcoming', 'sap', 'implementation']
['over', 'the', 'next', 'few', 'weeks', ',', 'project', 'apollo', 'and', 'beyond', 'will', 'conduct', 'its', 'final', 'sap']

我需要通过电子邮件发送此电子邮件,但它会逐行分隔。所以我想要的是每一行都由一封电子邮件代表。

1 个答案:

答案 0 :(得分:0)

您可以将整个文本文件读入一个变量,然后根据需要进行操作。只需将for line in f替换为data=f.read()。因此,在下面,我将每个txt文件读入数据变量,然后拆分以“”分隔单词。希望这会有所帮助。

for name in files:
    try:
        with open(name) as f:
            data = f.read().replace("\n","") 
        print(data.split())
    except IOError as exc:
        if exc.errno != errno.EISDIR:
            raise

输出看起来像这样:

['Subject:', 'key', 'dates', 'and', 'impact', 'of', 'upcoming', 'sap', 'implementationover', 'the', 'next', 'few', 'weeks', ',', 'project', 'apollo', 'and', 'beyond', 'will', 'conduct', 'its', 'final', 'sapimplementation', ')', 'this', 'implementation', 'will', 'impact', 'approximately', '12', ',', '000', 'newusers', 'plus', 'all', 'existing', 'system', 'users', '.', 'sap', 'brings', 'a', 'new', 'dynamic', 'to', 'enron', ',enhancing', 'the', 'timely', 'flow', 'and', 'sharing', 'of', 'specific', 'project', ',', 'human', 'resources', ',procurement', ',', 'and', 'financial', 'information', 'across', 'business', 'units', 'and', 'acrosscontinents', '.this', 'final', 'implementation', 'will', 'retire', 'multiple', ',', 'disparate', 'systems', 'and', 'replacethem', 'with', 'a', 'common', ',', 'integrated', 'system', 'encompassing', 'many', 'processes', 'includingpayroll', ',', 'timekeeping', '...']```