filename has a method called abspath that returns an object with the absolute path. You can cast that to a string.
...
from path import Path
folder_path = Path('/home/munk/folder/')
filename = folder_path.joinpath('foo')
absolute_path = filename.abspath()
print(absolute_path) # '/home/munk/folder/foo'
f = open(absolute_path, 'r')
UPDATE 2023-03-24: Actually use abspath + use the up to date path library
Answer from munk on Stack OverflowHello all, beginner here. Trying to write a small function that does the following:
-
Reads the current directory of files
-
Then allows the user to chose 1 file from the printed list
-
Stores that chosen file's absolute filepath to a string
Source code below:
import os
filesFound = os.listdir(os.getcwd())
for num, file in enumerate(filesFound):
print(f"#{num}: {file}")
filepath = filesFound[num]
directory = os.path.dirname(filepath)
choice = int(input ("\nChoose one\n\n"))
print("Chosen: " + filesFound[choice] + "\n")
print("File chosen path is: \n" + os.path.dirname(filesFound[choice]))Any help/corrections are greatly appreciated.
python - Convert a str to path type? - Stack Overflow
How do I convert path like object to a simple string/list element.
Windows path to Python path
python - How can I convert a pathlib.Path object to a string? - Stack Overflow
filename has a method called abspath that returns an object with the absolute path. You can cast that to a string.
...
from path import Path
folder_path = Path('/home/munk/folder/')
filename = folder_path.joinpath('foo')
absolute_path = filename.abspath()
print(absolute_path) # '/home/munk/folder/foo'
f = open(absolute_path, 'r')
UPDATE 2023-03-24: Actually use abspath + use the up to date path library
Python 3
from pathlib import Path
path = Path('~/folder/foo')
absolute_path = path.absolute().as_posix()
Python 2
import os
absolute_path = os.path.abspath('~/folder/foo').as_posix()
Since python 3.4:
from pathlib import Path
str_path = "my_path"
path = Path(str_path)
https://docs.python.org/3/library/pathlib.html#module-pathlib
Maybe that answer worked for python 2.7, if you are on Python 3 I like:
import os
p = "my/path/to/file.py"
os.path.normpath(p)
'my\\path\\to\\file.py'
For example, take this list of WindowsPath objects:
for item in paths:
print(item)
OUTPUT:
WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0001'), WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0002'), WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0003')When I do:
for item in paths:
print(str(item))
OUTPUT:
WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0001'), WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0002'), WindowsPath('C:/Users/ezbie/Programming/tweepina/bd/profile/0003')This is a constant problem I'm having, we use paths as path-like objects, but everywhere in the code we also need them as strings or iterables, but when we cast them we have to slice the string.
I have been searching the web for a solution without a result.
I made this small script that can be used. Feel free to use it.
I wonder is there a better solution on the issue to convert windows path to python path?
"""
A path, in Windows "C:\Folder" . in Python it is "C:/Folder".
In Python the "\" character can get interpreted as the ESCAPE character.
When an 'r' or 'R' prefix is present, a character following a backslash is
included in the string without change, and all backslashes are left in the string.
"""
def main():
# - YOUR INPUT - IMPORTANT: keep the r in front of path string here.
win_path = r"<TYPE YOUR PATH HERE>"
# Call function to convert from windows to Python path.
path_py = py_path(win_path)
print("Your Python Path: ", path_py)
def py_path(win_path):
python_path = "" # The result of this script.
# Convert to ASCII list
ascii_values_list = []
for character in win_path:
ascii_values_list.append(ord(character))
# Replace all ASCII values for "\" (=92) with value for "/" (=47).
for i in range(0, len(ascii_values_list)):
if ascii_values_list[i] == 92:
ascii_values_list[i] = 47
path_py = "" # Convert ASCII list to string
for val in ascii_values_list:
path_py = path_py + chr(val)
if path_py[-1] != "/": # Add "/" at end of path if needed.
path_py = path_py + "/"
return path_py
if __name__ == "__main__":
main() # Script goes there.
# EOF