python 3.5 open() function won't work - python

Currently going through a course on Python which is using 2.7. I have 3.5 installed and have been able to translate thus far. I'm having problems with the open() function. For example: see script and result below.
errno2
I have the file "textfile.txt" in the same folder as the .py file I'm running. As a check, I also put the file in the Python35 folder.. Any suggestions?

"same folder as the .py file I'm running" -- open() will search relative to your current working directory, regardless of the py source file's location.
From datamodel docs:
__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file
You can use __file__ and os.path.dirname() to find the directory of the source file and from there look for the text file.

Related

How to get the path to the directory where the .exe file is located after Pyinstaller compiles python script

I have an app that accesses .txt files that contains user data from a subdirectory where the .py file is located. After Pyinstaller is used to compile the .py file to a .exe file the path changed to AppData\Local\Temp\_MEI185962\<subdirectory>\<user data.txt> when I print the path. My question is how do I come up with the path to where the .exe file is all the time, because I want to make my program be distributeable so I don't want to use a hardcoded path or if I move the folder around.
So for example if I have my program.exe in the directory C:/Users/<username>/Desktop/project then how do I access te subdirectory C:/Users/<username>/Desktop/project/data. I tried importing os.path and had
path.dirname(path.realpath(__file__))
to get the path, but it is still pointing to the C:\User\<username>\AppData\Local\Temp\_MEI185962\<subdirectory>\<user data.txt>.
I am new to compiling so I don't know much about pyinstaller at all. I also can't seem to find any thing on this issue either.

Why SublimeREPL won't import a Python module or read a file in CWD?

I'm using Sublime Text 3 build 3126 on Ubuntu Zesty with the SublimeREPL plugin.
I open a Python REPL with CTRL+SHIFT+P >> SublimeREPL: Python and send a file to REPL with CTRL+, , F and evertyhing works as long as I work on a single Python script file. As soon as I try to move some parts of my code to another module and import it in the main file, I get the nasty ImportError: No module named error.
Trying to open a text file located in the same directory with:
codecs.open('filename', encoding='utf-8')
results in:
IOError: [Errno 2] No such file or directory: 'filename'
Did you investigate whether there was a relation between the file/panel from where you opened SublimeREPL: Python and the output of print os.getcwd()? SublimeREPL initializes its cwd at its startup of the REPL. The cwd will stay for the entire lifetime of the REPL.
As you pointed out, the default cwd for SublimeREPL: Python is:
"cwd": "$file_path"
This means that starting SublimeREPL: Python with your cursor in a blank Sublime panel, results in /opt/sublime_text/ as the cwd. This could be considered undesired and confusing.
However, if you start SublimeREPL: Python while your cursor is in the .py file that you want to run, the REPL will use the folder of your current .py file as its cwd.
Personally I think this is the desired behaviour, but you have to know it before it becomes convenient.
If you change the settings for the cwd to:
"cwd": "$folder",
the above behaviour of the stays unchanged for cases where you're not using sublime-projects. When you do use a sublime-project, the python REPL cwd will be the main project folder, independent of the cursor location at REPL startup. This might be the desired behaviour if you have a python-driven project. However, if you are just using some python scripts in a bigger project, you probably don't want your main project folder to be the cwd in the python REPL.
I spent a full day tearing my hair out while trying to find a solution to this problem.
First I thought there is some problem with $PYTHONPATH. I followed clues given in this (closed) issue on the SublimeREPL GitHub page: https://github.com/wuub/SublimeREPL/issues/355
And while the solution given by the plugin's author didn't work, adding the PYTHONPATH variable containing a path to my working directory to the extend_env key in Packages/SublimeREPL/config/Python/Main.sublime-menu solved the failing imports problem.
I thought I was golden, then I tried to read a text file in Python and got the IOError. Then it finally got to me that the wrong CWD (current working directory) was the culprit.
As the Python docs specify:
"When a module named spam is imported, the interpreter first searches
for a built-in module with that name. If not found, it then searches
for a file named spam.py in a list of directories given by the
variable sys.path. sys.path is initialized from these locations:
the directory containing the input script (or the current directory).
PYTHONPATH (a list of directory names, with the same syntax as the
shell variable PATH). the installation-dependent default.
I tried import os and print os.getcwd() in the REPL promt and surely what I got was:
/opt/sublime_text/
So what I did? The solution was a simple change to a line in Packages/SublimeREPL/config/Python/Main.sublime-menu (in a section corresponding to the REPL I was using). From:
"cwd": "$file_path",
to:
"cwd": "$folder",
Now calling os.getcwd() resulted in a path to the directory containing the file I sent to SublimeREPL and everything worked. Why $file_path gives '/opt/sublime_text' rather than the path to a file is either a question to the plugin's author or some underlying quirk with my system.

How do I read json content from python file that I have made into an executable (Mac)

I recently compiled my first python program into a standalone executable. There is one problem however. My python program originally accessed a .json file within the same directory and wrote contents to it. Now that I have made my python file into an exec file, it does not seem to access the .json file in the same directory anymore. Please help!
I guess the problem occurs because the the executable is not in the same folder as your script.
I can suggest you this solution:
import os
# csfp - current script folder path
csfp = os.path.dirname(os.path.realpath(__file__))
json_file = os.path.join(csfp, "config.json")
And you do whatever you want to do with this json_file variable, that contains the path and the name of your json file (example C:\Some_folder\My_python_project\config.json)

Using PYC file instead of a PY

A rookie question here:
I have a PY code and compiled it to create a .pyc. I would want to use this pyc file instead of PY.
I am running the PY file using external program. When the PY exists in the folder everything works perfect. However when I remove the PY file and simply use the pyc I get error:
IOError: [Errno 2] No such file or directory: 'E:/data/test/tech.py'
Whereas I have a tech.pyc lying around in the same folder.Any ideas what could be the issue here?
Normally, python is not compiled. The .pyc files are only a performance optimization that improve loading times.
Python is looking for the .py file because it always checks that first. If a .pyc file is newer than its corresponding .py file, it will then use the .pyc file. If the .py file is newer it will create a new .pyc file.

Understanding python compile

I seen the some difference when I execute the .py file. I have observed two cases,
1) when I run the .py file using the python mypython.py
I got the result. But .pyc file not created in my folder.
2) when I run the .py file using the python -c "import mypython"
I got the same result. But .pyc file was created in my folder.
My question is why first case not created .pyc file ?
Import is generally used when you need to use the contents of a file in another script or program, see What does python file extensions, .pyc .pyd .pyo stand for?. So to more specifically answer the question, the .pyc is created to ease access to the contents of the file in the future and is only created when the import command is used.
Python saves the precompiled .pyc file only for imported modules, not for the main script you're running.
Running a program as main or importing it as a module is not the exact same thing, but very similar because in a module everything that is at top level is executed at import time.
Note that for main program the source code is completely parsed and compiled too (so for example if you have a syntax error in last line nothing will be executed). The difference is only that the result of compilation is not saved back to disk.

Categories

Resources