简体   繁体   English

在Python中合并多个.txt / csv文件

[英]Merge multiple .txt/csv files in Python

I have multiple .txt files in a directory and I want to merge them into one by importing in python. 我在目录中有多个.txt文件,我想通过导入python将它们合并为一个。 The catch here is that after the merge I want to convert it into one csv file on which the whole program is based. 这里的问题是,合并之后,我想将其转换为整个程序所基于的一个csv文件。

So far I only had to input one .txt file and converted it into csv file by this code: 到目前为止,我只需要输入一个.txt文件,并通过以下代码将其转换为csv文件:

import io
bytes = open('XYZ.txt', 'rb').read()
df=pd.read_csv(io.StringIO(bytes.decode('utf-8')), sep='\t', parse_dates=['Time'] )
df.head()

Now I need to input multiple .txt files, merge them and then convert them into csv files. 现在,我需要输入多个.txt文件,将它们合并,然后将它们转换为csv文件。 Any workaround? 任何解决方法?

If the headers are same then it should be as easy as this 如果标题相同,则应该像这样简单

import os
import io

merged_df = pd.DataFrame()
for file in os.listdir("PATH_OF_DIRECTORY"):
    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))
import glob
path="location/of/folder"
allFiles = glob.glob(path + "\\*.txt")

list_ = []
for file in allFiles:
    print(file)
    df = pd.read_csv(io.StringIO(file.decode('utf-8')), sep='\t', parse_dates=['Time'])
    list_.append(df)
combined_files = pd.concat(list_)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM