简体   繁体   中英

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

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)

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')) 

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM