0

im trying to pass the "file" as variable to the function "processEntry". But if i pass the variable as an argument, my program doesn't find the file.

import pandas as pd
import os, sys
PATH = os.path.dirname(os.path.abspath(__file__))

def processEntry(file):  
    print("Processing...")
       
    try:
        pathToFile = os.path.join(PATH, file)
        df = pd.read_excel(pathToFile)

        print("Done!")
        return df

    except FileNotFoundError:
        print('File not found')


if __name__ == '__main__':
    file = 'test.xlsx'
    processEntry(file)

Result:

Processing... File not found

The problem isn't the path or the file, because exist: I create a variable inside the function to test it with the exact same value as "file", and the program find my file as it should be. (Same code, but using "internalVariableFile" inside the function with exact the same string as "file"):

import pandas as pd
import os, sys
PATH = os.path.dirname(os.path.abspath(__file__))

def processEntry(file):  
    print("Processing...")
    internalVariableFile = 'test.xlsx'   
    try:
        pathToFile = os.path.join(PATH, internalVariableFile)
        df = pd.read_excel(pathToFile)

        print("Done!")
        return df

    except FileNotFoundError:
        print('File not found')


if __name__ == '__main__':
    file = 'test.xlsx'
    processEntry(file)

Result:

Processing... Done!

Someone can help me? I want to pass the file as an argument to the function, and i dont know why the first code didn't work. Thanks!

Aser fc
  • 9
  • 1
  • 1
    Which precise file exists, and what exactly are you passing as the argument to the function? It tries to look in the directory where the code itself is saved, which is probably a design error. See also [What exactly is current working directory?](https://stackoverflow.com/questions/45591428/what-exactly-is-current-working-directory/66860904) – tripleee Jul 13 '21 at 13:21
  • @tripleee im passing the variable "file = 'test.xlsx'" . I also tried to print the variable "pathToFile" in both cases and the path was exactly the same, but the first code doesn't find the file and the other yes. – Aser fc Jul 13 '21 at 13:40

0 Answers0