No such file or directory using Python

Question:

I am trying to write a program in python where it reads a list of usernames from a file and sends a request to instagram to see if the username is available or not. Then it should prompt a message saying "THIS USERNAME IS AVAILABLE" or otherwise "THIS USERNAME IS TAKEN". I am having an error when trying to read my file that states ‘FileNotFoundError: [Errno 2] No such file or directory: ‘list.txt’, even though the file is in my folder where the program resides.

I am also fairly new to python.

Here is my code currently:

import requests
filepath = 'list.txt'
separator = "n" #Every time you use a newline it detects it as a new user
list  = open(filepath, "r").read().split(separator)
notTaken = []
for i in list :
    response = requests.get("https://instagram.com/" + i + "/")
    if response.status_code == 404 :
        notTaken.append(i)
Asked By: user14390434

||

Answers:

It worked in my case. My list.txt was in the same directory as my python file

import requests
with open('list.txt','r') as f:
    data = f.read().split("n")

for i in data:
    pass
    #...(write the rest of the code)
Answered By: user13786942

Use the absolute directory for that file i.e /home/directory/file_name if you are using window else use c:\\directory\file_name
this is if the file is not in the current working directory of the terminal. If you are in the same directory of the file in the terminal, use./file_name

Answered By: Ekure Edem

Since the file is in the same directory as your program, your code will only work if the current working directory is also that same directory. If you want to run this program from anywhere, you need a way to find that directory.

When python executes a script or module it adds a __file__ variable giving the path. (Extension modules and modules in compressed packages may not have this variable). The __file__ path can be relative to the current working directory or absolute. The pathlib library gives us a handy method for working with paths. So,

from pathlib import Path
separator = "n" #Every time you use a newline it detects it as a new user
filename = 'list.txt'
# get absolute path, then parent directory, then add my file name
filepath = Path(__file__).resolve().parent/filename
mylist = filepath.open().read().split(separator)

Since a "n" newline is used to demark the file, you don’t need to split it yourself. You could do this instead

mylist = filepath.open().readlines()
Answered By: tdelaney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.