Home > Software engineering >  FileNotFoundError: [Errno 2] No such file or directory (Python 3.10)
FileNotFoundError: [Errno 2] No such file or directory (Python 3.10)

Time:08-30

I am defining the path to the file and joining the path. When I run the test it is adding the double backslashes to the path and throwing the error "FileNotFoundError: [Errno 2] No such file or directory"

example:

Test.py

test_file_path = 'C:\folder1\folder2\folder3'
test_file_name = test_file_path   "Resultfile"   '_Test.xlsx'

======

test_result_file = Test.test_file_name
print("test_result_file")

when executing this I am receiving an error:

FileNotFoundError: [Errno 2] No such file or directory: "C:\\Folder1\\Folder2\\Folder3\\Resultfile_Test.xlsx"

CodePudding user response:

Can you try os.path for building file location and share the output? In comments, I wasn't able to add formatted code.

from os import path

class Test:
    test_file_name = None
    test_file_path = path.join("C:\\", "folder1", "folder2", "folder3")
    if path.exists(test_file_path):
        test_file_name = path.join(test_file_path, "Resultfile"   '_Test.xlsx')
        if path.exists(test_file_name):
            print(f"File exists, path: {test_file_name}")
        else:
            print(f"File does not exist, path: {test_file_name}")
    else:
        print(f"Folder does not exist, path: {test_file_path}")


test_result_file = Test.test_file_name
print(test_result_file)

CodePudding user response:

Why not simply do this?

import os.path

# stores whether given file exists or not
result = os.path.isfile(r'C:\folder1\folder2\folder3\Resultfile_Test.xlsx')
print(result)
  • Related