Published on

FileNotFoundError: [Errno 2] No such file or directory:

Authors

Last Modified : Sunday, Aug 18, 2024

Error

File "/home/ubuntu/sample1.txt", line 387, in main.py os.remove(local_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/ubuntu/sample1.txt'

Why did this error occured?

You get this error in python when file or directory that you are passing to python doesn't exists.

Solve 1

To solve this issue first verify that file or a folder already exists at that path. If it doesn't exists then you should create it and then pass it in python.

Solve 2

In python we can write a code to first check if file or folder exists or not as following

  • Check if file exists or not, this will return True or False.
import os
os.exists('/home/ubuntu/sample1.txt')
  • Check if folder exists or not, this will also return True or False.
import os 
os.path.isdir('local_folder')

Solve 3

Create file or folder if they don't exists. In python, if file or folder doesn't exists then we will create them as following

  • Create file
# first check if file exists or not
import os
if os.exists('/home/ubuntu/sample1.txt'):
    print("File exists.")
else:
    # this will create empty file
    file = open('/home/ubuntu/sample1.txt', 'x')
    file.close()
    print("New file created")
  • Create folder
import os
if os.path.isdir('local_folder'):
    print("Folder exists")
else:
    os.makedirs("local_folder")
    print("Folder created")

linux

os

python

pip