如何从多个 .txt 文件制作一个唯一的数据框?

How to make a unique dataframe from multiple .txt files?

我正在尝试从多个 .txt 文件制作数据框。可能重要的是,那些 .txt 文件曾经是 .dat 文件,我刚刚通过将 .dat 更改为 .txt 来转换它们。无论如何,它可以通过双击正常打开。

我的代码是:

path = "/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos/dados/17448"

files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)):
        files.append(i)

df = pd.DataFrame()
for i in files:
    frame = pd.read_csv(i)
    df = df.append(frame)
print(df)

输出为:

...

  File "pandas/_libs/parsers.pyx", line 384, in pandas._libs.parsers.TextReader.__cinit__

  File "pandas/_libs/parsers.pyx", line 695, in pandas._libs.parsers.TextReader._setup_parser_source

FileNotFoundError: File b'monitor_System_HumTechRoom.txt' does not exist

感谢您的帮助!

您的列表 "files" 仅包含目录 "path" 的内容,而不是其中文件的绝对路径。 Pandas 正在寻找 "monitor_System_HumTechRoom.txt" 而不是“/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos/dados/17448/monitor_System_HumTechRoom.txt”,因此出现 FileNotFoundError。 我是否正确理解您想将目录中的所有文件作为 csvs 读取到单个数据帧中,然后打印数据帧?

无需循环两次。尝试这样的事情:

csvdir = "/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos/dados/17448"

dataframes = []
for csv in os.listdir(csvdir):
    fullpath = os.path.join(csvdir, csv)
    if os.path.isfile(fullpath):
        # Read a csv into a dataframe and append to a list of dataframes
        dataframe = pd.read_csv(fullpath)
        dataframes.append(dataframe)

# Concatenate all created dataframes into one
df = pd.concat(dataframes)
print(df)