简体   繁体   中英

ValueError: Invalid file path or buffer object type: <class 'tuple'>

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

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.

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

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