Call a file in another folder in Eclipse for Python project - python

I have a small enough Python project in Eclipse Neon and keep getting the same error and can't find proper documentation on how to solve. In my main I need to call a file that is located in another folder. The error I receive is IOError: [Errno 2] No such file or directory:
I have an empty init.py file in the folder (XML_TXT) that I'm trying to use.

It looks like Groovy is importing okay, or else you would get an ImportError. An IOError indicates that it can't find "test.txt". Does that file exist?
It will work if the file path is relative to where you are running the script from. So for example if test.txt is in a folder
Groovy("folder_name/test.txt")
You can also go up in the directory structure if you need to, for example
Groovy("../folder_name/test.txt")
Or, if you want to be able to run the file from anywhere, you can have python work out the absolute path of the file for you.
import os
filename = os.path.join(os.path.dirname(__file__), 'folder_name/test.txt')
u = Groovy(filename)

Related

Running pyinstaller on code containing relative paths

I have a large python codebase developed inside PyCharm. I want to use PyInstaller for obvious reasons; however, I'm struggling with relative paths for data files due to the project code file hierarchy.
The file hierarchy was a usual top-down structure, i.e., the point of execution is within a file found in the project root folder, with the additional python files stored in a sensible folder, (please pay particular attention to the version.txt file on the same level as the Main.py file) e.g.,
Project/
--Main.py
--version.txt
--Engines/
----somefile.py
--Controllers/
----somefile.py
--Entities/
----somefile.py
A year ago, I built a GUI front end whilst maintaining the console-based point of execution. The GUI point of execution is within MainGUI.py. But that file is not at the project root. It looks a bit like this:
Project/
--Main.py
--version.txt
--GUI/
----MainGUI.py
--Engines/
----somefile.py
--Controllers/
----somefile.py
--Entities/
----somefile.py
Inside MainGUI.py, I have the code to open the "../version.txt" file:
with open("../version.txt") as file:
version = file.readline().strip()
I navigate to the Project/GUI folder in the PyCharm Terminal and execute pyinstaller MainGUI.py --onefile It seems to work until I try and execute the built MainGUI.exe. I'm given the error:
Traceback (most recent call last):
File "MainGUI.py", line 10, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '../version.txt'
[17232] Failed to execute script 'MainGUI' due to unhandled exception!
I could move the version.txt file to be on the same level as MainGUI.py, but this was a reduced example. There are lots of data files referenced using relative paths.
I would be grateful for any assistance. Thank you.

opening a .txt file

first, i'd like to mention that im using python via visual studio. not sure if this information will
be relevant but this is my first time using file input so i'm not sure
basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error 'FileNotFoundError: [Errno 2] No such file or directory'
is there a way to make it work or a different IDE i should use?
I tried reading a .txt file from the same location as my .py file. however, i keep getting the error 'FileNotFoundError: [Errno 2] No such file or directory'
Take into account that the script might not be running from the same path where your python script is and most probably your are not specifying the exact path of the file.
If your file is located in the same directory where your python sript is you can use the pathlib library this way to get your script to work:
import pathlib
# Some custom code
# find your current script path
current_script_path = pathlib.Path(__file__).parent
my_file_name = "my_file_name.txt"
# Specify the file path relative to your script's path
my_file_path = current_script_path / my_file_name
with open(my_file_path, "r+") as f:
print(f.read())

python - error occurs on relative path but not absolute path in macOS

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)

python code can't find file while its in folder marked as resource root in PyCharm

In PyCharm, I created folder named test, created txt file named test inside and marked folder as content root. When I added python file outside the test folder and tried to access test.txt file with open it suggested me file name. But when I tried running the code it couldn't find the file.
Traceback (most recent call last):
File "/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/testing.py", line 32, in <module>
print(open("test.txt").read())
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
This is how the code and folders look like ( ingore the trash folder)
How can I fix it? The main reason I am doing this is to avoid writing full path's for accessing file.
You are talking about two totally different things in your question. If you mark a folder as Sources root that means the Python interpreter will be able to find the modules in that folder.
For example:
When you write an own module and you want to use it in another file the Python won't find it automatically. The PYTHONPATH should contain the path of the folder which contains your module. And actually the Sources root option does this!
The other thing what you have mentioned in your question is that you don't provided a correct path in your code. It is a real error. In your code, you have to provide the correct path for open. The Pycharm is an IDE but your (or other's) Python interpreter will use your code.
You can solve your problem in many ways.
For example:
You can hard-code the path of your txt (It is totally not recommended):
print(open("/home/elmo/PycharmProjects/TBC_PAY_API_TESTING/test/text.txt").read())
You can use relative path:
print(open("test/text.txt").read())
You can use full path based on your Python file (I recommend this solution):
import os
dir = os.path.realpath(os.path.dirname(__file__)) # Directory of your Python file
file_path = os.path.join(dir, "test", "test.txt") # Create the path of the file
print(open(file_path).read())

Full File Path vs. Short OSX

I'm running OSX Mavericks but this problem has been going on since I had Snow Leopard.
When writing a script in any language, eg: Python. When I try to open a file the short
form doesn't work.
file = open('donkey.jpg')
And I get this error:
IOError: [Errno 2] No such file or directory: 'donkey.jpg'
Instead, I always have to specify the full path.
file = open('/Users/myName/Desktop/donkey.jpg')
Any ideas on why this could be happening and how to correct it?
If you specify donkey.png, it means donkey.jpg file in the current working directory. (relative path)
Make sure you're running the script in the same directory where donkey.jpg exists.
If you want specify the image file path relative to the script file instead of current working directory use following:
import os
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'donkey.jpg')
NOTE You can use __file__ only in script file. (not in interactive mode)
Your open call does not have a mode parameter. In which case, it defaults to opening the file in read mode.
Unless the file you are opening (to read) resides in the current working directory, it is completely expected that the python script throws a IOError.

Categories