将多个.txt文件作为数据帧加载到python中

时间:2019-10-19 19:41:29

标签: python file dataframe loading

我正在努力将多个.txt文件加载到桌面中的python中。我对Python完全陌生。我的目标是加载多个.txt文件,这些文件保存在同一目录中。 .txt文件是纯文本。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

您可以这样做。


from collections import defaultdict
from pathlib import Path
import pandas as df

my_dir_path = "/parh/to/folder"

results = defaultdict(list)
for file in Path(my_dir_path).iterdir():
    with open(file, "r") as file_open:
        results["file_name"] = file.name
        results["text"].append(file_open.read())
df = pd.DataFrame(results)

答案 1 :(得分:1)

这可能不必要地太长,但是如果需要,可以为文件名创建另一列:

sudo systemctl restart mongodb

答案 2 :(得分:0)

我会这样做。

import glob

read_files = glob.glob('C:\\your_path_here\\*.txt')

with open('result.txt', 'wb') as outfile:
    for f in read_files:
        with open(f, 'rb') as infile:
            outfile.write(infile.read())

我有5个文本文件,如下所示:

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.

最终结果如下:

FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.
FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.
FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.
FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.
FName,LName,Address
Jim,Bentz,34 Holloway La.
George,Hororitz,76 Ridge Dr.
Eric,Schimtz,11 Main St.