filenotfound error python (running through atom) - python

I'm working my way through the python crash course pdf. Everything was going well until I hit chapter 10 "files and exceptions".
The task is very simple.
1) create a text file "pi_digits.txt" that contains the first 30 digits of pi.
2) run the following code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
I keep getting a filenotfounderror [errno 2].
I have tried using the full file path, placing the file in the same ~.atom folder that contains the package 'script'.
I tried to run the file through a terminal and got the same error message.
I also searched stackoverflow for solutions and did find similar problems but the answers did not work.
Any help would be appreciated.

Prepend this:
import os
print(os.getcwd())
os.chdir('/tmp')
and copy the .txt file to /tmp. Also, be sure the copied filename is all lowercase, to match your program.

Related

How to fix FileNotFoundError?

I have encountered a problem while trying to open a .txt file from the same directory where my source code is located.
When I tried to open the file like this:
with open("pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I failed.
I also failed when I typed the whole path:
with open("Users\lukas\Documents\python_work\chapter_10") as file_object:
contents = file_object.read()
print(contents)
But when I typed:
with open("\\Users\\lukas\\Documents\\python_work\\chapter_10\\pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I succeeded!
So my question is: Why can't I run the code without error when I enter the following code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
Thank you for your answers and sorry if my question was not well constructed.
#Sottvogel
In general, a python instance can be run from many different directories in your computer. One way to check where the running instance is:
import os
os.getcwd()
If you confirm that you are in the same directory of your file, try and see
what the following returns:
os.listdir()
In case your file doesn't appear in the returned string, then there has to be another problem. Make sure you checkout the docs as well.
Hope it helps!
the thing with paths is python is that they are referenced from where you launch the program (current working directory), not from where the file lives. So, I recommend making use of the os and pathlib packages to manage file paths properly.
Why can't I run the code without error when I enter the following code:
It depends from where you execute your python code.
Building on above, where you execute your code implies wether you need to use the file name or it's path.
If you execute your Python code in the same directory as the txt file, then you can use the file's name. However, if it is located elsewhere the script will need to access the file and hence, requires the path to it.

Why does Python not find/recognise a file saved in the same directory as the file where the code is written?

I am quite new to working with Python files, and having a small issue. I am simply trying to print the name of a text file and its 'mode'.
Here is my code:
f = open('test.txt','r')
print(f.name)
print(f.mode)
f.close()
I have a saved a text file called 'test.txt' in the same directory as where I wrote the above code.
However, when I run the code, I get the following file not found error:
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
Any ideas what is causing this?
I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?
open (on pretty much any operating system) doesn't care where your program lies, but from which directory you are running it. (This is not specific to python, but how file operations work, and what a current working directory is.)
So, this is expected. You need to run python from the directory that test.txt is in.
I have also tried to replace the first argument above with the path of the test.txt file, but I get the same error?
In that case, you must have mistyped the path. Make sure there's no special characters (like backslashes) that python interprets specially in there, or use the raw string format r'...' instead of just '...'.
It depend from where the python command is launched for instance :
let suppose we have this 2 files :
dir1/dir2/code.py <- your code
dir1/dir2/test.txt
if you run your python commande from the dir1 directory it will not work because it will search for dir1/test.txt
you need to run the python commande from the same directory(dir2 in the example).

pandas cannot read csv in same directory

i am having this issue since like 2 months, it didnt bother me at first but now that im trying to import a file with pd or even a normal txt file with open() it gives me this Exception:
File "C:\Users\lcc_zarkos\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\common.py", line 642, in get_handle
handle = open(
FileNotFoundError: [Errno 2] No such file or directory: 'marketing.xlsx'
if i use the full path it just runs normally.
people would say "just use full path then" but this is a really bad solution when it comes to using this program on multiple devices with different paths or stuff like that
so i hope you have any solutions.
here is the code:
import pandas as pd
df = pd.read_csv('marketing.xlsx')
image:
vscode
folder
edit:
it has none to do with the code itself but more like windows or my pc
FileNotFoundError means that the file path you've given to pandas point to an non existing file.
In your case this can be caused by:
you haven't put your file in the current working directory of your script
you have a typo in your file name
In both case, I would print the file path, and check the location using a file browser, you will find your mistake:
print(os.path.join(os.getcwd(), 'marketing.xlsx'))
i see a spaces in the file name there. I tried on mac, and it works very well.
['main.py', 'marketing .xlsx', 'requirements.txt']

How to open a video file in python 2.7?

I am new to python, and I am trying to open a video file "This is the file.mp4" and then read the bytes from that file. I know I should be using open(filename, "rb"), however I am not clear about the following things:
In what directory is python looking for my file when I use open()? (My file is located in the downloads folder, should I move it? Where?
Is using "rb" the correct way to read the bytes from a file?
So far I tried to open the file and I get this error:
IOError: [Errno 2] No such file or directory: 'This is the file.mp4'
I know it is probably an obvious thing to do, however I have looked all over the internet and I still haven't found an answer.
Thank you in advance!
By default, Python opens the file from the current working directory, which is usually the folder where the .py script of the program is located.
If you move the video file in the same directory as the script, it should work.
You can also view the current working directory like this:
import os
print os.getcwd()
Also, instead of moving the file, you can just change "This is the file.mp4" to "C:/Users/<username>/Downloads/This is the file.mp4" if you are using Windows 7 and maybe 8. You will have to change the <username> to your computer username.
Wildcards might also work: "~/Downloads/This is the file.mp4"
Finally, what are you planning to do with the video file bytes? If you want to copy the file to somewhere else, there are modules to do that.
"rb" is a correct way to read bytes of a file.

Extracting .app from zip file in Python

(Python 2.7)
I have a program that will download a .zip file from a server, containing a .app file which I'd like to run. The .zip downloads fine from the server, and trying to extract it outside of Python works fine. However, when I try to extract the zip from Python, the .app doesn't run - it does not say the file is corrupted or damaged, it simply won't launch. I've tried this with other .app files, and I get the same problem, and was wondering if anyone else has had this problem before and a way to fix it?
The code I'm using:
for a in gArchives:
if (a['fname'].endswith(".build.zip") or a['fname'].endswith(".patch.zip")):
#try to extract: if not, delete corrupted zip
try :
zip_file = zipfile.ZipFile(a['fname'], 'r')
except:
os.remove(a['fname'])
for files in zip_file.namelist() :
#deletes local files in the zip that already exist
if os.path.exists(files) :
try :
os.remove(files)
except:
print("Cannot remove file")
try :
shutil.rmtree(files)
except:
print("Cannot remove directory")
try :
zip_file.extract(files)
except:
print("Extract failed")
zip_file.close()
I've also tried using zip_file.extractall(), and I get the same problem.
Testing on my macbook pro, the problem appears to be with the way Python extracts the files.
If you run
diff -r python_extracted_zip normal_extracted_zip
You will come into messages like this:
File Seashore.app/Contents/Frameworks/TIFF.framework/Resources is a directory while file here/Seashore.app/Contents/Frameworks/TIFF.framework/Resources is a regular file
So obviously the issue is with the filenames it's coming across as it's extracting them. You will need to implement some checking of the filenames as you extract them.
EDIT: It appears to be a bug within python 2.7.* as found here - Sourced from another question posted here.
Managed to resolve this myself - the problem was not to do with directories not being extracted correctly, but in fact with permissions as eri mentioned above.
When the files were being extracted with Python, the permissions were not being kept as they were inside the .zip, so all executable files were set to be not executable. This problem was resolved with a call to the following on all files I extracted, where 'path' is the path of the file:
os.chmod(path, 0755)

Categories