简体   繁体   中英

combining multiple text files into csv in python

I have 2 text files:

文本文件 1文本文件 2

I want to make a CSV file with the data and add a column based on the header. Like this:

预期产出 .

I wrote this:

import glob 
import pandas as pd

files = sorted(glob.glob('content/*.txt'))
df = pd.concat(map(pd.read_csv, files))

df.to_csv(r"C:\Users\srava\OneDrive - Deakin University\Desktop\final\combined.csv")

But the output doesn't match what I want:

输出

I will break your problem into 3 parts:

  1. Get column name from header. For that I will read it using read_csv. But it may not be most optimised way. But it will do for small files.
  2. Read all files and skip first row. Give same column names.
  3. Add column with respective header value. We can achieve it using following code:
 import glob import pandas as pd files = sorted(glob.glob('content/*.txt')) dfs = [] for file in files: column_name = pd.read_csv(file,index_col=False).columns[0] df = pd.read_csv(file,index_col=False,names=["col1","col2"],skiprows=1) df["col3"] = column_name dfs.append(df) df = pd.concat(dfs)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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