How to convert any .csv file to an excel file using Python?

Question:

I’m trying to convert any .csv file from this path to an excel file. The code works but I need to rename that .csv file manually. Is there a way to read and convert whatever .csv file without renaming it? Your input is highly appreciated. Thanks a lot!

import pandas as pd

read_file = pd.read_csv(r'C:/Processed_Report/Source1.csv')
read_file.to_excel (r'C:/Processed_Report/Source.xlsx', index = None, header=True)
Asked By: QuickSilver42

||

Answers:

I don’t sure if i understood, but this is how you can read all file inside a folder and convert them to excel files.

import os

for root, dirs, files in os.walk("C:/Processed_Report/", topdown=False):
    for name in files:
        base_name, ext = os.path.splitext(name)  #Split name, extension
        if ext in ".cvs":
            df = pd.read_csv(os.path.join(root, name))
            df.to_excel(os.path.join(root, f'{base_name}.xlsx')) 
Answered By: Cristian Festi

Using pathlib

from pathlib import Path

import pandas as pd


file_path = r"C:/Processed_Report"
files = [x for x in Path(file_path).glob("*csv")]
[pd.read_csv(x).to_excel(f"{file_path}/{x.stem}.xlsx", index=False) for x in files]
Answered By: Jason Baker
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.