[Python] python script to merge all files in a directory into one [closed]

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    i'm trying to merge two .csv files from the same directory and create a new .csv file as a result. What is the way to do this with python? Here is what I attempted so far with no success.


    import pandas as pd
    import os

    def merge_csv_files(r'S:\PW\Lead Service Reports from NorthStar\2025\INDEX_DIRECTORY', output_files):
    all_files = os.listdir(r'S:\PW\Lead Service Notification\Lead Service Reports from NorthStar\2025\INDEX_DIRECTORY')
    csv_files = [files for file in all_files if files.endswith(".csv")]

    all_df = []
    for file in csv_files:
    file_path = os.path.join(directory, file)
    df = pd.read_csv(file_path)
    all_df.append(df)

    merged_df = pd.concat(all_df, ignore_index= True)
    merged_df.to_csv(output_file, index = False)
    print("merged")


    thanks GJ

    Continue reading...

Compartilhe esta Página