Please check your current directory.
For that just do this:
import os
print (os.getcwd())
Answer from Roman Belousov on Stack Overflowfr = open("alice.txt", "r")
t = fr.read()
fr.close()
Error code:
Traceback (most recent call last):
File "C:/Users/Vincent/PycharmProjects/pythonProject/Python chopping function.py", line 1, in <module>
fr = open("alice.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
Comment:
I don't know where to paste the file alice.txt. I pasted it in the python folder but it still can't find the file.
hey guys I'm I'm trying to read in a file thats in the same folder as my script but i get an error saying it doesn't exist. any help would be greatly appriciated
So I wrote a small bit of python that is theoretically supposed to look for numbers and sum them all up in a file.... So I downloaded a file and typed it in the code, but python keeps on not being able to do it: "FileNotFoundError: [Errno 2] No such file or directory: 'NumberExtractSum' "
I didn't make a typo and I tried .txt, which brought me to the question: where should the file be?
If there is another error pls tell me heres the code lol:
import re
lst = list()
file = open(input('Your File:'), 'r')
for line in file :
----y = re.findall('[0-9]+', line)
----for x in y :
--------z = int(x)
--------lst.append(z)
print(sum(list))
Hello, I created a EXE using pyinstaller from within the terminal in pycharm. Video on how I did this here: https://youtu.be/bqNvkAfTvIc
My error message is in comments. Can anyone help to troubleshoot why my exe is not finding my input file that exists in the folder?
Hey Everyone,
I am currently trying to write an automation script that does the following:
-
Log into a website
-
Download Excel file from website
-
Put file in folder
-
Rename file
-
Format file accordingly
-
Send file to email list
Currently I'm stuck on step 4 which I feel should be the easiest but I keep running into an error. Long story short is that Python is telling me the file or directory doesnt exist when it does.
Below is my code, thank you to anyone who takes the time to look into this. Also please let me know if you need additional information.
now = datetime.today()
days_since_sunday = (now.weekday()-6) % 7
last_sunday = now -timedelta(days=days_since_sunday)
formatted_date = last_sunday.strftime('%#m/%d/%Y')
file_path = r"C:\Users\adoucette\Desktop\DOT_Weekly\sqlexec.xlsx"
new_file_path = r"C:\Users\adoucette\Desktop\DOT_Weekly\DOT Weekly Sales WE " + formatted_date + ".xlsx"
shutil.move(file_path, new_file_path)
Error is:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\adoucette\\Desktop\\DOT_Weekly'
EDIT: Thanks for the responses everyone! Truly apprecaite all the help you've given me. i am going to try to make a folder that is not synced to Onedrive to see if that works....stay tuned!
EDIT #2: It was the One Drive folder all along, I created a folder outside of my Desktop so that it wouldnt be synced by One Drive and it worked! Thanks to everyone for commenting and trying to help a newbie like me out.
Please check your current directory.
For that just do this:
import os
print (os.getcwd())
I had this same issue. I was using VS Code for my IDE, and had the folder setting to a folder above where I had the file. This obviously was the issue. Once I opened the folder in VScode where the code and the text file were both located I was able to open the file with no issues.
I have a folder on my desktop, named 'folder', and a python file and a text file called 'output.txt' in it. Inside the .py file I have:
output = open('C://Desktop/folder/output.txt', 'w')
output.write(2**38)
output.closebut python can't find the file. What's the correct way of doing this?
Are you using the slashes that you have in your post, or are you using Windows-style backslashs (\)? regular slashes don't need to be escaped (doubled), backslashes need to be escaped or entered as a raw string. Pick one of these options:
output = open('C:/Desktop/folder/output.txt', 'w')
output = open(r'C:\Desktop\folder\output.txt', 'w')
output = open('C:\\Desktop\\folder\\output.txt', 'w')
Also, you can't write a number to a file; only strings can be written to a file. Convert the number to a string before you write it:
output.write(str(2**38))
And thirdly, you need () on the end of your output.close(). Or use the with syntax, which closes the file automatically:
with open('C:/Desktop/folder/output.txt', 'w') as output:
output.write(str(2**38))
What is the exact error message you're getting?
Does open('output.txt', 'w') work?
So the code I have is:
f = open("input.txt","r")
where input.txt is an already made file in the same folder as the program. The error that pops up states that it cannot find the file (I believe it was errorno 2 or something like that). I have changed the "r" to "w" and tried to create a new file by that name, but it states that there is already a file under that name.
Is the problem due notepad ++ not being able to find it or am I missing/ doing something wrong?
Thank you in advance!
(SOLVED)
For anyone having the same issue in the future: I got this problem from using commands at the terminal, while following the harvard CS50 course on youtube.
Whenever I tried running python file_name.py through the terminal for different files, I got the error: "can't open file 'C:\\Users\\... : [Errno 2] No such file or directory".
This came up from the code at the 5:22:15 mark, and the cowsay code at the 5:40:03 mark.
1st code:
import sys
if len(sys.argv) < 2:
print("too few arguments")
elif len(sys.argv) > 2:
print("too many arguments")
else:
print("hello, my name is ", sys.argv[1])2nd code:
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.cow("hello, " + sys.argv[1])Solution: the second comment by u/aishiteruyovivi - in layman's terms: you have to change the directory from the shell's root directory to the folder wherein your file is located.
Hi,
I'm working on an exercise from Python Crash Course, and I'm getting this error, even though both my program file and the read file are in the same directory/folder: FileNotFoundError: [Errno 2] No such file or directory: 'learning_python.txt'
This is the code i'm running:
from pathlib import Path
print("--- Reading in the entire file:")
path = Path('learning_python.txt')
contents = path.read_text()
print(contents)
print("\n--- Looping over the lines:")
lines = contents.splitlines()
for line in lines:
print(line)
I'm only getting the error when I run the program on VS Code, when I run it in Sublime Text the program runs with no issues.
Does anyone have any suggestions on what might be the problem and how to fix it?
Thanks in advance.
I am dealing with a pretty mysterious situation.
I have a directory of four files - including one called "iterate.py" and one called "urls".
If I am in this directory and launch a Python shell, the command "json.load(open("urls"))" works perfectly.
However, I wrote that line of code inside the "iterate.py" script, and I am running it in VS Code with breakpoints, in the debugger.
I am repeatedly getting the message that "No such file", on that line of code.
I simply can't understand how this command could work in a Python shell in that directory but not when run from a script in that directory.
I cannot figure out if this is an issue of scope, or if something happens when you run a Python script in the VS Code debugger.
Can anyone please help me?
Thanks very much
On a Mac.
I've been able to use py2app to run a script that includes Pandas.
It basically inputs two files, and outputs one.
My difficulty is that I can't find anywhere how to reference local files. If I hard code it with directory
pd.read_csv("~/test_file.csv"), it only works if I include the file in the build.
Has anyone been able to build something that will search the local directory, then output a file, and make it standalone so that a user doesn't have to know Python or worry about installs?
My stack overflow and GitHub, etc hasn't yielded much luck for Python Pandas Compile, but I'm open to links as well!
I'm trying to start learning Python again from scratch and I need the smallest amount of help to get started. I did a tiny bit of Python in college, but all the computers were running Linux and all I have now is a Windows 10 laptop. I'm not interested in dual boot or getting another machine just for Linux, I want to understand how to do things on my Windows laptop.
I downloaded Python 3.9.6 again today. I would like to be explained two things.
-
how do I create a file named "quicktest dot py" (if I write that with .py at the end, it creates a link for whatever reason) that just contains two lines, for example : 'print("hello")' and 'print("bye")'.
I've tried using IDLE but it's impossible to hit "enter" without resetting the damn thing, now I'm just confused how to write a multiple line code. And how to edit it, as well, once you've ran it once. This isn't quite how I remember things from college.
2) how do I execute that file
I can learn all the Python code in the world with online resources, but if I can't find any resource that explains to laymen how to create, save and run a .py file, that's not very helpful, is it? I didn't find much, except jargon-drop pages where I didn't get an explanation I could understand. I have a Master's degree in math, so I hope I can say i'm not a complete idiot, but I'm not exactly a tech-savvy person, or a very computer-literate guy, and I don't code ever. I want to get into it for math purposes though, and it's the most basic things that are in my way right now.
Thanks for your help.
Okay thank you everyone, I got what I wanted (for now, lol). Now I can get started properly.
-
You may find it useful to explore any of the free IDEs that are available for Python and build in more functionality (such as Visual Studio Code, PyCharm, or Spyder), but you can absolutely just write code in a text editor. Even Notepad.
2)Typically you would open a command prompt (press the Windows key and type cmd), navigate to the folder that has your .py file and type
python whateveryounamedthefile.py
Change your import in test.py to:
from .hello import hello1
Your code is fine, I suspect your problem is how you are launching it.
You need to launch python from your '2014_07_13_test' directory.
Open up a command prompt and 'cd' into your '2014_07_13_test' directory.
For instance:
$ cd /path/to/2014_07_13_test
$ python test.py
If you cannot 'cd' into the directory like this you can add it to sys.path
In test.py:
import sys, os
sys.path.append('/path/to/2014_07_13_test')
Or set/edit the PYTHONPATH
And all should be well...
...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'
There is a better shebang you should use.
Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.
[Solved] I am an idiot. I had a folder called KanjiDrag, and within that I had the actual source folder kanji_drag which is where the json file and the main module were. The path I was using was accessing the KanjiDrag folder, but not the kanji_drag folder, and I didn't catch the different names. This is my dumbest file IO mistake yet. Thanks for all the replies, many of which I'll still refer to later when I refine this part of my program. Upvotes for everyone!
Hi, all. I'm running into a "no such file or directory" issue in python that I can't figure out.
I'm using windows 7, and I have the file in the same directory as the program I'm running. I got this error, so then I tried using the absolute path (the file is still in the same working directory anyway) and still got the same error. I even checked with os.getcwd and os.path.abspath and copy-pasted the path exactly.
I'm not sure what's going on here. I closed every program that could possibly be running the file. Would I be getting this error if the file is still open in some elusive background program?
This is the relevant bit of code:
print(os.getcwd())
print(os.path.abspath('RainyGenki1&2.json'))
deckName = "C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki1&2.json"
deck = open(deckName, 'r') #opens card deckwindows is going on.
backslashes are special characters in strings.
annoyingly windows uses them to seperate paths.
to print a backslash you need to escape it with a backslash
print("\\")
There are two things to try. We usually don't use the ...\\... approach because it isn't portable and it's really easy to forget to do it (or miss one backslash).
You can use forward slashes in Windows now, I believe:
deckName = "C:/Users/myName/My Documents/myfile.txt"
And you can compose a path with raw strings:
deckName = r"C:\Users\myName\My Documents\LiClipse Workspace\KanjiDrag\RainyGenki1&2.json"
Try those out.
Another portable approach is to use the os.path functions (doc here) that use the directory separator characters appropriate to your operating system:
import os.path
path = os.path.join(BaseDirectory, 'subdir1', 'subdir2')
will give you C:\Test\subdir1\subdir1 on windows and /Test/subdir1/subdir2 on other operating systems. Also useful is the os.path.expanduser() function.
It's always a good idea if you can't seem to open a file that you know exists to compose the complete path in a string variable which you print when the operation fails.
BaseDir = r"C:\Test"
path = os.path.join(BaseDirectory, 'subdir1', 'subdir2')
try:
fp = open(path, 'r')
except IOError:
print("IOError: for file '%s'" % path)
raise
# file opened succesfully