将 txt 文件合并为一个,保留不同文件中重复项的最新行

Merge txt files into one, keeping the latest rows of the duplicates that come in different files

这里的挑战包括将大型 txt 文件(有些大 70MB,总共 3GB 数据)合并为一个供 BI 系统读取的文件。有些行在多个文件中重复,合并后的文件需要有最新的行。

我不是开发人员,但我正在通过正确的方式学习来解决这个问题。与此同时,我正在尝试解决编码问题。这一次,我尝试了几个解决方案,下面的代码给了我一个 interesting/intriguing 结果:

import os
import io
import pandas as pd

merged_df = pd.DataFrame()
for file in os.listdir(r"C:\Users\username\Desktop\txt"):
    if file.endswith(".txt"):
        bytes = open(file, 'rb').read()
        merged_df = merged_df.append(pd.read_csv(io.StringIO(
            bytes.decode('utf-8')), sep="\t", parse_dates=['Time']))

print(len(merged_df))

我一直收到这个错误,它似乎得到了一个文件,但并没有识别它,也没有在任何地方写任何东西。

Traceback (most recent call last):
  File "<pyshell#11>", line 3, in <module>
    bytes = open(file, 'rb').read()
FileNotFoundError: [Errno 2] No such file or directory: 'FILENAME.txt'

非常感谢任何帮助!

您的问题是 os.listdir return 只是该文件夹中文件的文件名。它没有 return 完整路径。因此 open 将在您 运行 脚本所在的文件夹中查找具有该名称的文件。您需要将该文件名转换为绝对路径,例如通过执行

file_path = os.path.join(r"C:\Users\username\Desktop\txt", file)
bytes = open(file_path, 'rb').read()