How to convert read multiple text files from a folder and convert it into a single CSV file?

Question:

I am having text files in the format as given below.

ID                                     0x4607
Delivery_person_ID             INDORES13DEL02
Delivery_person_Age                 37.000000
Delivery_person_Ratings              4.900000
Restaurant_latitude                 22.745049
Restaurant_longitude                75.892471
Delivery_location_latitude          22.765049
Delivery_location_longitude         75.912471
Order_Date                         19-03-2022
Time_Orderd                             11:30
Time_Order_picked                       11:45
Weather conditions                      Sunny
Road_traffic_density                     High
Vehicle_condition                           2
Type_of_order                           Snack
Type_of_vehicle                    motorcycle
multiple_deliveries                  0.000000
Festival                                   No
City                                    Urban
Time_taken (min)                    24.000000
Name: 0, dtype: object

These files must be represented as single row in a CSV file.

Answers:

You should do something like:

import os
import pandas as pd

path = "Directory/"
df = pd.concat([pd.read_csv(f"path/{file}") for file in os.listdir(path) if ".csv" in file]
df.to_csv("save it here", index=False)
Answered By: Francisco Gonzalvo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.