No such file or directory using Python [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How do you properly determine the current script directory?
(16 answers)
Closed 6 months ago.
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)

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)

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

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

Related

Python can't find where my txt file is, how can i link it or where do i need to put the file?

Python can't find where my .txt file is, how can I find the correct path to it or where do I need to put the file?
I tried the following but got an error:
with open("C:\Users\raynaud\Downloads\notlar.txt","r",encoding="utf-8") as file:
with open("dosya.txt","r",encoding= "utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'dosya.txt'
If you are not using absolute path, you must place the file in the same directory as the script is. On absolute paths you should not use \ like "C:\Users\UserName\", because \ is the escape character in Python (and many more languages). You must use it like this: "C:\\Users\\UserName\\"
Have you checked your current directory? It might be pointing to somewhere unexpected. Try:
import os
os.getcwd()

Cannot access file in current working directory - 'FileNotFoundError: [Errno 2] No such file or directory'

I have seen multiple other questions regarding this but none that answer my question. I am getting the error
'FileNotFoundError: [Errno 2] No such file or directory:' even though my current working directory matches that of the location of the file.
I have tried hardcoding the file location using python ex15.py C:\Users\Matt\py\sample.txthowever i get 'FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\py\\sample.txt'
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your filename {filename}:")
print(txt.read())
print("Type the filename again")
file_again = input("> ")
variable
text_again = open(file_again)
print(txt_again.read())
Current working directory is C:\Users\Matt\py. When I try to hardcode it gives two backslashes (\) which I assume is causing an issue, but I would like to be able to do it without hardcoding anyway.
Thanks.
The problem is that your file is not actually called sample.txt. Its real name is sample.txt.txt. It just happens to look like sample.txt in the GUI because you're using Windows and you've told Windows Explorer to hide extensions in file names.
See also:
https://blogs.technet.microsoft.com/activedirectoryua/2013/05/22/how-to-see-those-file-extensions-in-windows/
https://answers.microsoft.com/en-us/windows/forum/windows_10-files/how-to-display-file-extensions-in-w-10/226d323d-978a-47de-bd1d-8780643897e3

Opening and Reading files in Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 3 months ago.
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:
If, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.
In short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.
Hope this helps!
image with terminal open on desktop and in text editor to show working directory difference
I used full path of the file along with r, which is for raw string. Worked for me.
example:
filename = **r**'C:\Python\CrashCourse\pi_digits.txt'
with open(filename) as file_object:
content = file_object.read()
print(content)
The path to the file is relative to where you run the python file from, not from where the python file is located.
Either run your code from the same directory as the files, or make the file path absolute, based on the python file's location.
import os
with open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:
contents = file_object.read()
print(contents)
Hope that helps
Try this:
with open('c:\\Workspace\\Crash Course\\Lessons\\Ch 10\\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
You can try getting the full path to the file
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
pi_digits = os.path.join(dir_path, 'pi_digits.txt')
with open(pi_digits, r) as file_object:
print(file_object.read())
You might have to enable "Execute in file dir"
vscode setting

Python filename if statement not working

I have a python script that I need to run from the windows command line. The line
for filename in os.listdir(os.getcwd() + "\\sampdirectory1\\sampdirectory2"):
if filename.startswith("sample.csv"):
os.remove("sample.csv")
keeps giving me the error
The system cannot find the file specified 'sample.csv'
Well the file doesn't exist yet, it's created in the script for the first time then edited by the script every time after that. What I don't understand is why it's trying the do os.remove on sample.csv, when the if statement should fail, meaning the remove shouldn't be reached.
You can't delete it while holding on to it because "On Windows, attempting to remove a file that is in use causes an exception to be raised"
https://docs.python.org/2/library/os.html#os.remove
There are 2 things to notice here:
first: the folder/destination are different. you should be using
os.remove(os.getcwd() + "\sampdirectory1\sampdirectory2" + "sample.csv")
second: a more elegant solution would be
try:
os.remove(os.getcwd() + "\\sampdirectory1\\sampdirectory2" + "sample.csv")
except:
print ('no such file/directory')
pass
There might be a file .\sampdirectory1\sampdirectory2\sample.csv, so the condition is valid. But you're trying to delete a file .\sample.csv (sample.csv in current directory) that doesn't exist and you're getting the error.
Moreover, there might be a file .\sampdirectory1\sampdirectory2\sample.csvSOMETHING, so the condition is still valid and you're getting the error.
You need to do os.remove(filename) instead of os.remove("sample.csv")
Because at first sample.csv is not the file that you are checking if it exists before removing. And even the filename is sample.csv you need to precise to full path of the file.
And as you are iterating over listing the directory files you don't need to check if the file exists.
So if you want to remove files whose names start with sample.csv, the code should be as below:
for filename in os.listdir(os.getcwd() + "\\sampdirectory1\\sampdirectory2"):
if filename.startswith("sample.csv"):
os.remove(filename)
But if you want to remove only sample.csv, then you don't need any loop. Just do
filename = os.path.join(os.getcwd(), "sampdirectory1\\sampdirectory2\\sample.csv")
if os.path.exists(filename):
os.remove(filename)

use Python to open a file in read mode

I am trying to open a file in read mode using Python. The error I am receiving suggest I am using the won filename or read mode. When I type the file path into my computer, it works. I tried to assign the input filename to a variable and then opening the variable in read mode. I also tried typing in the full path and opening the path in read mode. Both game me an error.
Code:
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
def calculateZscore():
"Z score calc"
full_original = os.path.join(workingDirec,original_file)
print full_original
f = open ('C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt','r')
print f
My results:
Using full path output:
What is the working directory?C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data
The input filename is?NCSIDS_ObsExp.txt
C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt'
Using variable output:
IOError: [Errno 2] No such file or directory: 'full_original'
On Windows your paths must be escaped because Windows uses backslashes \ to denote path separators.
Backslashes however are typically used as escape sequences and are used in Python as such as well! So you have to "escape" them like this:
f = open ('C:\\Users\\tpmorris\\ProgramingAndScripting\\Trial 2 Data\\Trial 2 Data\\NCSIDS_ObsExp.txt','r')
See:
Windows path in Python
Using Python on Windows
Firstly , on Windows, you must escape backslashes (double backslash) if you are going to use Windows path syntax, for the reasons pointed out by #James Mills answer.
Another option is to use forward slashes; Python will interpret these correctly in os.path.
You could use as your command line path input:
C:/Users/tpmorris/ProgramingAndScripting/Trial 2 Data/Trial 2 Data
Or add
/NCSIDS_ObsExp.txt
to the above if you were going to use a hardcoded path.
Also you should make some small changes to your code if you want to print the contents of your text file:
First, your file open should be done using a with statement. This will ensure the file object's built in __enter__ and __exit__ methods get called, in particular, if you forget to close the file when you are done after you've opened it.
See Understanding Python's with statement for more.
Second, if you want to print each line in your text file, don't try to print the file object. Rather loop through the lines and print them.
So your code for accepting command line input should be:
import os
workingDirec = raw_input("What is the working directory?")
original_file = raw_input("The input filename is?")
full_original = os.path.join(workingDirec,original_file)
print full_original
with open(full_original,'r') as f:
for line in f:
print line
f.close()
I removed the def of a function to do something else in the midst of your file read code. That def should go elsewhere.

Categories

Resources