Home > Back-end >  ValueError: Invalid file path or buffer object type: <class 'tuple'>
ValueError: Invalid file path or buffer object type: <class 'tuple'>

Time:12-28

Here is a simplified version of some code that I have. Running this version of the code results in the error: ValueError: Invalid file path or buffer object type: <class 'tuple'>

I wanna open the excel file ultimo_arquivo.

import os
import pandas as pd

caminho = "C://Users/MM165193/Downloads"

lista_arquivos = os.listdir(caminho)

lista_datas = []

for arquivo in lista_arquivos:
    data = os.path.getmtime(f"{caminho}/{arquivo}")
    lista_datas.append((data, arquivo))
    
lista_datas.sort(reverse=True)
ultimo_arquivo = lista_datas[0]

pd.read_excel(ultimo_arquivo, engine="openpyxl")

CodePudding user response:

It looks like the problem is with the ultimo_arquivo variable. It should be a string representing the file path or a file-like object, but it appears to be a tuple.

To fix the issue, you can modify the line where you assign ultimo_arquivo to only include the file name rather than the tuple. You can do this by changing this line:

Copy code ultimo_arquivo = lista_datas[0] to this:

Copy code ultimo_arquivo = lista_datas[0][1] This will set ultimo_arquivo to the file name of the most recently modified file in the directory, rather than the tuple containing the modification time and file name.

Then, you can use ultimo_arquivo as the argument to pd.read_excel() like this:

Copy code pd.read_excel(f"{caminho}/{ultimo_arquivo}", engine="openpyxl") This should fix the error and allow you to read the Excel file.

CodePudding user response:

import os import pandas as pd

caminho = "C://Users/MM165193/Downloads"

lista_arquivos = os.listdir(caminho)

lista_datas = []

for arquivo in lista_arquivos: data = os.path.getmtime(f"{caminho}/{arquivo}") lista_datas.append((data, arquivo))

lista_datas.sort(reverse=True) ultimo_arquivo = lista_datas[0]

pd.read_excel(ultimo_arquivo, engine="openpyxl")

  • Related