how to COMBINE CSV FILES using PYTHON (Step by Step)

Published: 13 October 2024
on channel: Ferds the NetDev
209
4

In this video, I talk about how to compile multiple CSV files into one file. See the code below that you can just run right away and it should work.

*************
import pandas as pd
from pathlib import Path

Step 1: Get the directory where the script is located
script_dir = Path(__file__).parent

Step 2: List all CSV files in the directory using a for loop and if statement
csv_files = []
for f in script_dir.iterdir():
if f.suffix == '.csv':
csv_files.append(f)

Step 3: Initialize an empty list to hold dataframes
dataframes = []

Step 4: Loop through the list of CSV files and read each one into a dataframe
for file in csv_files:
df = pd.read_csv(file)
dataframes.append(df)

Step 5: Concatenate all dataframes into a single dataframe
combined_df = pd.concat(dataframes, ignore_index=True)

Step 6: Save the combined dataframe to a new CSV file
output_file = script_dir / 'combined_output.csv'
combined_df.to_csv(output_file, index=False)

Step 7: Print a confirmation message
print(f"Data from {len(csv_files)} files has been combined and saved to {output_file}")
*************

#python #programming #pythonforbeginners


On this page of the site you can watch the video online how to COMBINE CSV FILES using PYTHON (Step by Step) with a duration of hours minute second in good quality, which was uploaded by the user Ferds the NetDev 13 October 2024, share the link with friends and acquaintances, this video has already been watched 209 times on youtube and it was liked by 4 viewers. Enjoy your viewing!