I have 2 text files:
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:
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.