Home > front end >  Convert files from diferent paths using python
Convert files from diferent paths using python

Time:08-04

I´m trying to convert excel files from diferent paths but it only converts the file in the last path in path list.

What is the proper way to loop trough the paths in the list to to get the files to be converted?

import pandas as pd
import glob, os
import csv, json
import openpyxl
from pathlib import Path


list_path = Path("excel_files/PLM", "excel_files/PTR", "excel_files/TMR")
for xlsx_file in glob.glob(os.path.join(list_path,"*.xlsx*")):
    data_xls = pd.read_excel(xlsx_file, 'Relatório - DADOS', index_col=None, engine = 'openpyxl')
    csv_file = os.path.splitext(xlsx_file)[0] ".csv"
    data_xls.to_csv(csv_file, encoding='utf-8', index=False)

CodePudding user response:

Path("excel_files/PLM", "excel_files/PTR", "excel_files/TMR") returns a single path, not a list of paths:

>>> Path("excel_files/PLM", "excel_files/PTR", "excel_files/TMR")
PosixPath('excel_files/PLM/excel_files/PTR/excel_files/TMR')

I'm not sure why it finds any files at all, to be honest.

Instead, you will probably have to do another loop - something like:

for path in ["excel_files/PLM", "excel_files/PTR", "excel_files/TMR"]:
    for xlsx_file in glob.glob(os.path.join(path, "*.xlsx*")):
        ...
  • Related