I have a path to some file:
'home/user/directory/filename'
I want get the filename-subpart. The main problem is, I don't know the length of my string and I don't know the length of filename-subpart. I know just that filename is placed at the end of a string after the last slash /. The number of slashes in the string could be absolutely random (because I want get the filename from every directory on some PC).
Consequently I don't see for now the usual method with index extraction, like this:
string[number:]
Any ideas?
To get the basename use os.path.basename:
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split()
from os import path
pth = 'home/user/directory/filename'
print(path.basename(pth))
filename
Or str.rsplit:
print(pth.rsplit("/",1)[1])
filename
If you were trying to index a string from the last occurrence you would use rindex:
print(pth[pth.rindex("/") + 1:])
You could try this also,
>>> import os
>>> s = 'home/user/directory/filename'
>>> os.path.split(s)[1]
'filename'
Related
I am trying to replace a string here in Python.
This is my Input -
link = (r"C:\dell\Documents\Ms\Realm")
I want my output to be like this:
C:/dell/Documents/Ms/Realm
I tried the replace method it didn't work.
the code tried:
link = (r"C:\dell\Documents\Ms\Realm")
link.replace("\","/")
In Python strings, the backslash "\" is a special character, also called the "escape" character. You need to add second backslash to "escape" it and use in string search.
link.replace("\\", "/")
There's nothing wrong with that Windows path. There's no reason to replace anything. A real improvement would be to use pathlib instead of raw strings:
from pathlib import Path
link = Path(r"C:\dell\Documents\Ms\Realm")
That would allow you to construct paths from parts using, eg joinpath, get the parts of the path with parts, the name with name, directory with parent etc.
var filePath=link.joinpath("some_file.txt")
print(filePath)
-------------------
C:\dell\Documents\Ms\Realm\some_file.txt
and more
>>> print(link.parts)
('C:\\', 'dell', 'Documents', 'Ms', 'Realm')
>>> print(link.parent)
C:\dell\Documents\Ms
Or search for files in a folder recursively:
var files=(for file in link.rglob("*.txt") if file.is_file())
I have a given file path. For example, "C:\Users\cobyk\Downloads\GrassyPath.jpg". I would like to pull in a separate string, the image file name.
I'm assuming the best way to do that is to start from the back end of the string, find the final slash and then take the characters following that slash. Is there a method to do this already or will I have search through the string via a for loop, find the last slash myself, and then do the transferring manually?
The pathlib module makes it very easy to access individual parts of a file path like the final path component:
from pathlib import Path
image_path = Path(r"C:\Users\cobyk\Downloads\GrassyPath.jpg")
print(image_path.name) # -> GrassyPath.jpg
You can certainly search manually as you've suggested. However, the Python standard library already has, as you suspected, a function which does this for you.
import os
file_name = os.path.basename(r'C:\Users\cobyk\Downloads\GrassyPath.jpg')
I am trying to list files with specific ending ('.txt') in folder which was set as a variable, using python.
I tried to use glob.glob('userFolder/*.txt') in order to do it.
import os
import glob
userFolder='/homes/myFolder'
glob.glob('userFolder/*.txt')
I got an empty list.
The text userFolder in your glob() call is just part of the string value, it's not related to the variable with the same name. If it was, you could never use something like print or os or any other variable name directly in a string.
You could just use + to concatenate the variable value with the glob pattern:
text_files = glob.glob(userFolder + '/*.txt')
but the better method is to use os.path.join() to handle path construction:
files = glob.glob(os.path.join(userFolder, '*.txt'))
Another option is to use the [pathlib module], which has its own glob support:
import pathlib
userFolder = pathlib.Path('/homes/myFolder')
text_files = userFolder.glob('*.txt')
i have a list with filenames. How do i use the os.path.splitext() function to split the suffix and a filename and wirte it again into a list without the suffix.
import os
image_names = os.listdir('C:\Pictures\Sample Pictures')
newimageList = []
for name in image_names:
newimageList.append(name.os.path.splitext())
print(newList)
unfortunately the code don't work i get an Error: 'str' object has no attribute 'os'
if i had a new list(separeted in filename and suffix) i would skip every second element in a list to get just the filenames
According to the docs, you should try os.path.splitext('/desired_path').
You just have to adjust your code...
So, instead of:
newimageList.append(name.os.path.splitext())
Use:
newimageList.append(os.path.splitext(name))
You want os.path.splitext(name) instead of name.os.path.splitext().
Say that I have this string "D:\Users\Zache\Downloads\example.obj" and I want to copy another file to the same directory as example.obj. How do I do this in a way that´s not hardcoded?
"example" can also be something else (user input). I'm using filedialog2 to get the big string.
This is for an exporter with a basic GUI.
os.path.dirname() gives you the directory portion of a given filename:
>>> import os.path
>>> os.path.dirname(r"D:\Users\Zache\Downloads\example.obj")
'D:\\Users\\Zache\\Downloads'
You can solve it with str.split but this should be solved with os.path.split