'How to rename columns in multiple csv files in a folder?
I have two csv files in a folder
https://www.dropbox.com/sh/jyu2rj2ra01vuvb/AADht6uAhJcjnSjIFpNufVlka?dl=0
How to rename the columns of all the files in the folder as the following
S.No Fruit Vendor Price
Input:
Expected Output:
File df1
S.No Fruit VendorA PriceA
1 Apple AB 89
2 Banana CA 72
File df2
S.No Fruit VendorB PriceB
1 Mango AB 55
2 Watermelon BC 23
Expected Output:
File df1
S.No Fruit Vendor Price
1 Apple AB 89
2 Banana CA 72
File df2
S.No Fruit Vendor Price
1 Mango AB 55
2 Watermelon BC 23
Solution 1:[1]
Read the file in pandas dataframes:
df = pd.read_csv('df1.csv')
Assign a column list with the names that you want
col_list = ['S.No','Fruit','Vendor','Price']
Assign this col list to the dataframe
df.columns = col_list
Write this dataframe into another csv
df.to_csv('new_df1.csv', index=False)
Do this for all dataframes. Let me know if this helps.
Solution 2:[2]
If you don't stricly required to use pandas. There are other solution that will perform way better than panda.
import shutil
import glob
files = glob.glob(".\*.csv")
for i in range(len(files)):
from_file = open(files[i])
to_file = open(files[i], mode="w")
to_file.write("S.No,Fruit,Vendor,Price\n")
shutil.copyfileobj(from_file, to_file)
This way you can get all the files in the folder with .csv extention. Also you don't even read a single line. So that this will work way faster if you csv file gets bigger.
Solution 3:[3]
you can just use this:
files = ['df1.csv', 'df2.csv']
for file in files:
with open(file, 'r') as f:
data = f.readlines()
data[0] = 'S.no,Fruit,Vendor,Price'+'\n'
with open(file, 'w') as f:
for element in data:
f.write(element)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mayank Porwal |
| Solution 2 | ?hsan Cemil Çiçek |
| Solution 3 | hhaefliger |
