I have multiple CSV files in one directory but with no headers. I'm looking for a robust way to add same headers to all files in my directory at once.
Sample.csv:
John Doe Guitar 4 units
Desired output after adding headers 'name', 'product', 'quantity':
name product quantity
John Doe Guitar 4 units
so far I found a way to add headers into a single file with pandas:
from pandas import read_csv
df = read_csv('/path/to/my/file/Sample.csv')
df.columns = ['name', 'product', 'quantity']
df.to_csv('/path/to/my/file/output.csv')
now I guess I would have to add a loop that would read all files in my directory and add desired header row into each. Could someone help me with this step or suggest some other easier approach if possible? Thank you in advance.
attempting to add loop but it throws an error message:
import pandas as pd
import os
import glob
from pandas import read_csv
path = '/path/to/my/files/'
filelist = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
list = []
frame = pd.DataFrame()
#whenever i run the below line it throws this error -> IndentationError: expected an indented block
for file in filelist:
df2 = pd.read_csv(path+file)
df2.columns = ['name', 'product', 'qunatity']
list.append(df2)
frame = pd.concat(list)