Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遍历目录中的文件,并使用pandas将结果写入数据帧的新行_Python_Excel_Pandas - Fatal编程技术网

Python 遍历目录中的文件,并使用pandas将结果写入数据帧的新行

Python 遍历目录中的文件,并使用pandas将结果写入数据帧的新行,python,excel,pandas,Python,Excel,Pandas,我想迭代目录中的文件,提取一些信息,并使用pandas将其写入excel工作表。 我有这段代码,但只有当我迭代一个文件(没有循环)时才有效,当我使用循环并尝试迭代所有文件时,输出是一个空的excel工作表 import re import os import pandas as pd files=[i for i in os.listdir("path") if i.endswith("txt")] for file in files: f=open((file), 'r') d

我想迭代目录中的文件,提取一些信息,并使用pandas将其写入excel工作表。 我有这段代码,但只有当我迭代一个文件(没有循环)时才有效,当我使用循环并尝试迭代所有文件时,输出是一个空的excel工作表

import re
import os
import pandas as pd
files=[i for i in os.listdir("path") if i.endswith("txt")]
for file in files:
    f=open((file), 'r')
    data=f.read()
    a=re.findall(r'Company Name(.*?)Type',data,re.DOTALL)
    a1="".join(a).replace('\n',' ')
    b=re.findall(r'Sector(.*?)Sub Sector',data,re.DOTALL)
    b1="".join(b).replace('\n',' ')
    w={'Company Name': [a1], 'Sector': [b1]}
    df=pd.DataFrame(data=w)
    print (os.path.join(file))
df.to_excel(r'/Users/nameuser/info.xlsx') 
我看到它遍历所有文件,但这样输出是空的

我该如何做才能使我从每个文件中获取的所有信息累积起来并存储到excel文件的新行中

import re
import os
import pandas as pd

files=[i for i in os.listdir("path") if i.endswith("txt")]

w={'Company Name': [], 'Sector': []}

for file in files:

    f=open((file), 'r')
    data=f.read()
    a=re.findall(r'Company Name(.*?)Type',data,re.DOTALL)
    a1="".join(a).replace('\n',' ')
    b=re.findall(r'Sector(.*?)Sub Sector',data,re.DOTALL)
    b1="".join(b).replace('\n',' ')
    w['Company Name'].append(a1) 
    w['Sector'].append(b1)

    print (os.path.join(file))

df=pd.DataFrame(data=w)
df.to_excel(r'/Users/nameuser/info.xlsx')

通过这种方式,您可以将所有数据作为dict填充,然后将其转换为数据帧。

我猜您只保存到循环中的最后一个df。