Python I/O cannot find file, but path seems OK - python

I am with a python script. I want to open a file to retrieve data inside. I add the right path to sys.path:
sys.path.append('F:\WORK\SIMILITUDE\ALGOCODE')
sys.path.append('F:\WORK\SIMILITUDE\ALGOCODE\DTW')
More precisely, the file file.txt I will open is in DTW folder, and I also add upper folder ALGOCODE. Then, I have command
inputASTM170512 = open("file.txt","r")
I have this present:
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
inputASTM170512 = open("ASTM-170512.txt","r")
IOError: [Errno 2] No such file or directory: 'ASTM-170512.txt'
Why? Do you have any idea?

open() checks only the current working directory and does not traverse your system path looking for the file. Only import works with that mechanism.
You will either need to change your working directory before you open the file, with os.chdir(PATH) or to include the entire path when trying to open it.

When you try to open file with open, for example:
open("ASTM-170512.txt","r")
you will try to open a file in the current directory.
It does not depend on sys.path. The sys.path variable is used when you try to import modules, but not when you open files.
You need to specify the full path to file in the open or change the current directory to the correspondent place (I think that the former is better).

Related

Playsound python module can't find file even in same folder

I have imported the playsound python module and put a mp3 file in the same folder as the python file, and yet when I run the file all I get is an error message saying
open Sound.mp3
Cannot find the specified file. Make sure the path and filename are correct.
Error 263 for command:
close Sound.mp3
The specified device is not open or is not recognized by MCI.
Failed to close the file: Sound.mp3
Traceback (most recent call last):
File lookup is usually relative to the current working directory and not the Python source file itself. You could either run the script from the directory with the sound file (cd /path/to/sound_files, python3 /path_to_script), or pass and absolute path to the sound file when calling playsound.
If you're using an IDE, the working directory can usually be set in the run configuration.

open() method not working in JupyterLab ( pyspark kernel )

Getting below error when running the command:
output = open( "C:/Users/TAA3656/mytddutc_nudges_sample.json", 'w') # Update to local path and file name
[Errno 2] No such file or directory: 'C:/Users/TAA3656/mytddutc_nudges_sample.json'
Traceback (most recent call last):
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/TAA3656/mytddutc_nudges_sample.json'
I'd guess the path C:/Users/TAA3656 doesn't exist, so it's not possible to create a file in this nonexistent path. For example:
>>> open("nonexistent/thing.json", 'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent/thing.json'
One could think that open(..., 'w') should create nonexistent/thing.json if it doesn't exist, but in this case, the directory nonexistent is... non-existent, so open refuses to create the file along with an entire path structure.
You should create the path first:
from pathlib import Path
the_path = Path("C:/Users/TAA3656")
# Create the path if it doesn't exist
the_path.mkdir(parents=True, exist_ok=True)
# Open or create the file
with (the_path / "your_file.json").open("w") as output:
... # run your code
verify the path of the file you are trying to open is correct. to verft the path exist use !pwd to show the path you are in and navegate to the location and !mkdir name to create the folder and the you can acces it.you also need to import sys and import os. so you can navegate through the system files
Do you know if you are running your jupyterlab locally, or in some kind of cloud environment? (Your mention of a pyspark kernel suggests to me it may be the latter.) If it is a cloud platform of some kind, you may not have access to your local hard disk.
Try this to check your platform, and see if it looks local to you.
Or you can try:
import os
os.getcwd()
to give you the path of where you are currently working. If it doesn't look like a directory on your local pc, again, you not be working locally.
Or ask a friendly looking colleague.

How to fix "No such file or directory: 'AppleStore.csv'"?

I have a csv file and I put it at D:\Subin\PYTHON\AppleStore.csv
Then I launch my Jupyter Notebook with the url: http://localhost:8888/notebooks/PYTHON/test.ipynb
I try to run this script:
open_file = open('AppleStore.csv')
Then I get the issue:
FileNotFoundError Traceback (most recent call last)
<ipython-input-25-7784a3a20685> in <module>
----> 1 open_file = open('AppleStore.csv')
FileNotFoundError: [Errno 2] No such file or directory: 'AppleStore.csv'
the test.ipynb is at same directory with AppleStore.csv But I dont understand why I got file not found issue.
Anyone have idea about this?
If you are running python from within Jupyter, your working directly is likely where Juptyer is installed. Within your notebook, use print("my path is ", os.getcwd()) to check what your working directory is. (credit to gelonida)
Either use the full path to the file, or change your current working directory to the folder where the file is. os.chdir(FOLDER PATH GOES HERE)
For both of the code samples in this answer, you'll need to first import os.

Opening a file in Python gives me errors

I am quite new to Python and I am having problems opening a file in Python.
I want to open a text file called 'coolStuff' in a Folder on my Desktop and this is how I type in the command but I still get an error message. The file exists and so I do not understand why I get that error message.
open("coolStuff.txt","r")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
open("coolStuff.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'coolStuff.txt'
If you want to simply supply a filename like coolStuff.txt without also providing a full directory, then you have to make sure that Python is running in the same directory as the file. If you aren't sure what directory Python is running in, try this:
import os
print(os.getcwd())
You have two options:
let's say your file is in C:\path\to\dir\coolStuff.txt
1.
open(r'C:\path\to\dir\coolStuff.txt','r')
2.
import os
os.chdir(r'c:\path\to\dir')
open('coolStuff.txt', 'r')
Because the file you want to open is not in the current directory.You can find the file 'coolStuff.txt' in the terminal and launch your python environment at the same directory.

Py2exe isn't copying webdriver_prefs.json into builds

I'm using py2exe to compile a Python 2.7 script that uses Selenium 2.39.0 to open up Firefox windows and carry out some routines. In the past, I've been able to compile the code without any issue. Today though, after updating from Selenium 2.35 to 2.39, I'm running into trouble. When I try to run the .exe generated by the compiled code, I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyo", line 1410, in __call__
File "literatureonlineapi2.5.5.py", line 321, in startapi
File "selenium\webdriver\firefox\webdriver.pyo", line 43, in __init__
File "selenium\webdriver\firefox\firefox_profile.pyo", line 58, in __init__
IOError: [Errno 2] No such file or directory: 'C:\\Text\\Professional\\Digital H
umanities\\Programming Languages\\Python\\Query Literature Online\\LION 1.0\\2.5
\\2.5.5\\dist\\.\\selenium\\webdriver\\firefox\\webdriver_prefs.json'
Here we go!
Exception in Tkinter callback
Traceback (most recent call last):
File "Tkinter.pyo", line 1410, in __call__
File "literatureonlineapi2.5.5.py", line 321, in startapi
File "selenium\webdriver\firefox\webdriver.pyo", line 43, in __init__
File "selenium\webdriver\firefox\firefox_profile.pyo", line 58, in __init__
IOError: [Errno 2] No such file or directory: 'C:\\Text\\Professional\\Digital H
umanities\\Programming Languages\\Python\\Query Literature Online\\LION 1.0\\2.5
\\2.5.5\\dist\\.\\selenium\\webdriver\\firefox\\webdriver_prefs.json'
(This error does not appear when I run the uncompiled code.)
I came across a google code page that led me to believe newer versions of Selenium have had trouble with this missing webdriver_prefs.json file, but that didn't help me sort out the problem.
Does anyone know how I might manually provide the missing file? I would be grateful for any help others can offer.
I found a solution, and thought I would post it in case others have a similar problem. I found the missing webdriver_prefs.json file tucked away in
C:\Python27\Lib\site-packages\selenium-2.39.0-py2.7.egg\selenium\webdriver\firefox\
After I had navigated to that directory, I grabbed the webdriver_prefs.json file and the webdriver.xpi file. I then copied both of those files into
dist\selenium\webdriver\firefox\
created by py2exe, and was able to run the compiled code as expected. God save the queen.
I did the following to fix the problem:
Create a sub-folder \selenium\webdriver\firefox\ under dist.
Under command DOS prompt, enter python.exe setup_firefox.py
You could either running the executable under dist or copy all the files under "dist" to your own directory and run the executable from there.
Here is my setup_firefox.py:
from distutils.core import setup
import py2exe,sys,os
sys.argv.append('py2exe')
setup(
console=[{'script':"test.py"}],
options={
"py2exe":{
"skip_archive": True,
"unbuffered": True,
"optimize": 2
},
}
)
I had a related issue for which I have found a work round...
My issue
I was trying to run a python script that uses Selenium 2.48.0 and worked fine on the development machine but failed to open Firefox when py2exe'ed with the error message:
[Errno 2] No such file or directory:'C:\test\dist\library.zip\selenium\webdriver\firefox\webdriver_prefs.json'
Cause
I traced the problem to the following file in the selenium package
C:\Python27\Lib\site-packages\selenium\webdriver\firefox\firefox_profile.py
It was trying to open webdriver_prefs.json and webdriver.xpifrom the same parent directory
This works fine when running on the development machine but when the script is run through py2exe firefox_profile.pyc is added to library.zip but webdriver_prefs.json and webdriver.xpi aren't.
Even if you manual add these files to appropriate location in the zip file you will still get the 'file not found' message.
I think this is because the Selenium file can't cope with opening files from within the zip file.
Work Round
My work round was to get py2exe to copy the two missing files to the dist directory and then modify firefox_profile.py to check the directory string.
If it contained .zip modify the string to look in the parent directory
webdriver_prefs.json
class FirefoxProfile(object):
def __init__(self, profile_directory=None):
if not FirefoxProfile.DEFAULT_PREFERENCES:
'''
The next couple of lines attempt to WEBDRIVER_PREFERENCES json file from the directory
that this file is located.
However if the calling script has been converted to an exe using py2exe this file will
now live within a zip file which will cause the open line to fail with a 'file not found'
message. I think this is because open can't cope with opening a file from within a zip file.
As a work round in our application py2exe will copy the preference to the parent directory
of the zip file and attempt to load it from there
'''
if '.zip' in os.path.join(os.path.dirname(__file__)) :
# find the parent dir that contains the zipfile
parentDir = __file__.split('.zip')[0]
configFile = os.path.join(os.path.dirname(parentDir), WEBDRIVER_PREFERENCES)
print "Running from within a zip file, using [%s]" % configFile
else:
configFile = os.path.join(os.path.dirname(__file__), WEBDRIVER_PREFERENCES)
with open(configFile) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs)
webdriver.xpi
def _install_extension(self, addon, unpack=True):
if addon == WEBDRIVER_EXT:
addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
tmpdir = None
xpifile = None
'''
The next couple of lines attempt to install the webdriver xpi from the directory
that this file is located.
However if the calling script has been converted to an exe using py2exe this file will
now live within a zip file which will cause the script to fail with a 'file not found'
message. I think this is because it can't cope with opening a file from within a zip file.
As a work round in our application py2exe will copy the .xpi to the parent directory
of the zip file and attempt to load it from there
'''
if '.zip' in addon :
# find the parent dir that contains the zipfile
parentDir = os.path.dirname(addon.split('.zip')[0])
addon = os.path.join(parentDir, os.path.basename(addon))
print "Running from within a zip file, using [%s]" % addon
if addon.endswith('.xpi'):
tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1])
compressed_file = zipfile.ZipFile(addon, 'r')
for name in compressed_file.namelist():
if name.endswith('/'):
if not os.path.isdir(os.path.join(tmpdir, name)):
os.makedirs(os.path.join(tmpdir, name))
else:
if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))):
os.makedirs(os.path.dirname(os.path.join(tmpdir, name)))
data = compressed_file.read(name)
with open(os.path.join(tmpdir, name), 'wb') as f:
f.write(data)
xpifile = addon
addon = tmpdir
I found the sulution, the py2exe can't open zip file. So after copy the webdriver_prefs.json and webdriver.xpi, decompression the library.zip into a folder named "library.zip"

Categories