Convert files from different paths using Python

Question:

I´m trying to convert Excel files from different 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)
Asked By: Bruno

||

Answers:

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*")):
        ...
Answered By: jfschaefer
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.