gpt4 book ai didi

python - 尝试将多个文本文件读入单个 pandas 数据帧时发生 FileNotFoundError

转载 作者:行者123 更新时间:2023-12-01 08:18:31 25 4
gpt4 key购买 nike

我尝试将本地目录中的多个文本文件读取到一个 pandas 数据帧中。由于原始文本文件带有额外的文件扩展名,所以我将其重命名,然后我尝试通过 read_csvconcatpandas 将所有文本文件读入单个数据帧。问题是,我可以使用 pandas 读取单个文本文件,但是当我尝试将本地目录中的文本文件列表读取到单个数据帧中时,出现以下错误:

folder = 'fakeNewsDatasets[Rada]/fakeNewsDataset/fake'
allfiles=os.listdir(folder)
print(allfiles)

['biz01.txt',
'biz02.txt',
'biz03.txt',
'biz04.txt',
'biz05.txt',
'biz06.txt']

然后我尝试将这些文本文件读入单个数据帧,如下所示:

dfs=pd.concat([pd.read_csv(file, header = None, sep = '\n', skip_blank_lines = True) for file in allfiles], axis=1)

*

FileNotFoundError: [Errno 2] File b'biz02.txt' does not exist: b'biz02.txt' *

我不明白为什么会出现这个问题,因为将单个文本文件读取到 pandas dataframe 对我来说效果很好。

df = pd.read_csv('biz01.txt', header = None, sep = '\n', skip_blank_lines = True)
df=df.T
df.columns = ['headline', 'text']

谁能帮我解决这个问题吗?我该如何修复这个错误?还有更好的主意吗?

最佳答案

使用glob()会更容易:

import glob
allfiles=glob.glob('C:\\folder1\\*.csv')

否则,在 pd.read_csv() 中读取文件时,您可能需要在执行 for file in allfiles 时将路径与 file 结合起来

关于python - 尝试将多个文本文件读入单个 pandas 数据帧时发生 FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54844177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com