How can I get the full path to a file without the file extension using .stem?
I have tried:
from pathlib import Path
for i,file in enumerate(os.listdir(os.environ['onedrive'])):
if file.endswith(".txt"):
print("Full file path without extension using stem:", os.path.realpath(file).stem)
Error:
AttributeError: 'str' object has no attribute 'stem'
perhaps I am calling the path to the file incorrectly, but I am not sure how else.
Related
My project directory tree is something like this,
build
----fonts
--------Roboto Bold.ttf
----main.py
The following code errors out,
from pyglet import font
font.add_file("fonts\\Roboto Bold.ttf")
Also tried this code,
import os
from pyglet import font
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
the error is,
Traceback (most recent call last):
File "{full_dir_name}\build\main.py", line 25, in <module>
font.add_file(str(os.getcwd())+'\\fonts\\Roboto Bold.ttf')
File "C:\python-3.8.5-amd64\lib\site-packages\pyglet\font\__init__.py", line 183, in add_file
font = open(font, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '{full_dir_name}\\fonts\\Roboto Bold.ttf'
I have tried about a day now and also seen other posts here but could not resolve...
The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd(). If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
font.add_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts/Roboto Bold.ttf"))
My input is a list of file names (as a list of variables) and I know the path to these files. Each file has a function called "test" and I have to call the "test" function from each of these files. The path is not my working directory. I need to be able to dynamically import these files.
I tried using importlib, but I get the following errors:
import importlib
importlib.import_module("..\..\foo", package=None)
TypeError: the 'package' argument is required to perform a relative import for '..\\..\\x0coo'
importlib.import_module("C:\Users\Desktop\foo", package=None)
ModuleNotFoundError: No module named 'C:\\Users\\Desktop\\foo'
How would I go about executing the function in a file, using the filename and path (both stored in variables)?
I'm not sure this is the best way, but I solved this by first adding the path to
the module to sys.path:
>>import sys
>>sys.path.append('/path/to/module')
>>mod=importlib.import_module('my_module_name')
then you can call functions in that module like this
>>mod.myfunc(myargs)
or, if you have the function name in a python string like func='myfunctionname'
you can call it like
>>mod.__dict__[func](args)
I'd need to see more code, but my first guess is that you need to replace \ with / in your Directory string, since \ escapes out of the string.
I have python 2.7 code with creates a builtin file object which return me a file object <type 'file'>
file(os.path.join('/tmp/test/', 'config.ini'))
Same code i changed in python 3.7 as below it returns <class '_io.TextIOWrapper'>
open(os.path.join('/tmp/test/', 'config.ini'))
How can i get a file object type in python 3
You can use them the exact same way.
file = open(os.path.join("/tmp/test/", "config.ini"))
print(file.read()) # Will print file contents
Or use pathlib:
from pathlib import Path
file = Path("/tmp/test") / "config.ini"
print(file.read_text()) # will do the same
You're not looking for a file object. You're looking for an object that'll let you read and write files.
I have Python module with single file and single function inside the file. I've uploaded it to pypi, and I used following structure to package it, but when I called the function which it inside module file I received this error:
AttributeError: module 'effInput' has no attribute 'ask'
('ask' is name of function).
Module package structure :
|--effInput
|--__init__. py
|--effInput.py (module file)
|--setup.py
|--readme.txt
|--LICENSE
init.py file:
import effInput
name="EffInput"
What I did wrong?
When you do it that way you have to call effInput.effInput.ask instead of effInput.ask. If you did from effInput import * in your __init__.py it should work as intended.
This is my directory structure
-directory1
|-currentlyWritingCode
-directory2
|-__init__.py
|-helper.py
|-view.ui
The helper.py is a UI from pyqt4 framework. It needs the view.ui file .
it has following code to load the ui data
viewBase, viewForm = uic.loadUiType("view.ui")
now in directory1 in the currently writing code I did this
import directory2.helper
when I run the code in currentlyWritingCode it is throwing an error that
FileNotFoundError: [Errno 2] No such file or directory: 'view.ui'
What to do now?
using python3.5 from anaconda on Centos 7
Use os.path.join(os.path.dirname(os.path.realpath(__file__)),'view.ui') in place of view.ui. This will ensure you correctly reference the folder that the python file lives in, regardless of the code that imports it.
Note: Make sure you have import os with your other imports.
How does this work?
__file__ is an attribute of the module you are importing. It contains the path to the module file. See this answer. However, this path is not necessarily an absolute path. os.path.realpath returns the absolute path (it even follows symlinks if there are any). At this point we have a full path to the module, so we take the path to the directory (os.path.dirname) and join it with the original filename (which we assumed to be relative to the original module and so should be in the aforementioned directory). os.path.join ensures that the correct \ or / is used when constructing a file path so that the code works on any platform.