Splitting string in python using multiple operations in one line [duplicate] - python

This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Closed 1 year ago.
I have the following:
selstim = '/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg'
I need to end up with:
43et1
I tried:
selstim.split('/')[-1]
Which produced:
43et1.jpg
I also tried:
selstim.split('/,.')[-1]
That doesn't get the desired result.
Is there a way to also get rid of the '.jpg' in the same line of code?

You may just find it easier to use pathlib (if you have Python 3.4+) and let it separate the path components for you:
>>> from pathlib import Path
>>> p = Path('/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg')
>>> p.stem
43et1

Implementation using only the standard os library.
from os import path
filePath = path.basename("/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg")
print(filePath) # 43et1.jpg
print(path.splitext(filePath)[0]) # 43et1, index at [1] is the file extension. (.jpg)
All in one line:
path.splitext(path.basename(FILE_PATH))[0]

Related

delete images containing specific word in its name using python [duplicate]

This question already has answers here:
How do i search directories and find files that match regex?
(4 answers)
Closed 8 months ago.
In the directory there are multiple images with names:
I want to delete all images with "340" in it using a python code.
Assuming that the images are in desktop/images/
I'm not sure why you need to use Python and can't just use your shell (in bash it would just be rm desktop/images/*340*)
But in Python I think the shortest way would be
import os, glob
for file in glob.glob("desktop/images/*340*"):
os.remove(file)
or even:
import os, glob
[os.remove(file) for file in glob.glob("desktop/images/*340*")]
You can use this example, you'll have to adjust the code for your correct directory:
import os
import re
for file in os.listdir("Desktop/Images"):
if re.search("340.*?\.jpg$", file):
os.remove("Desktop/Images/" + file)
print("Deleted " + file)
else:
print("No match for " + file)

How do i change Root(or starting directory) in python [duplicate]

This question already has answers here:
Get relative path from comparing two absolute paths
(6 answers)
Closed 1 year ago.
When i use os.getcwd() , it gives me something like this :
'/home/xxx/PycharmProjects/pythonProject3'
I want change it to something like this :
PycharmProjects/pythonProject3
in another word I wanna my os.getcwd() starts from where I want.
how can I do it?
i tried os.chdir and os.path.abspath(os.curdir) and it does not work.
I am using python3 and ubuntu.
Can you tell us how did you try chdir? Please see example below to change you current working director and let me know that output it gives on your machine.
>>> import os
>>> os.getcwd()
'/home/lllrnr101'
>>> os.chdir('/etc/')
>>> os.getcwd()
'/etc'
>>>

How to get a list with all filenames with full path along with extension [duplicate]

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 2 years ago.
I have one folder say ABC in which i have so many files with extension say 001.py, 001.xls, 001.pdf and many more. I want to write one program in which we get list with this filename say
["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
MyCode:
import os
from os import listdir
from os.path import isfile, join
dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path) #current path
cwd = os.getcwd()
list3 = []
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for i in onlyfiles:
list3.append(dir_path+"\\"+i)
print(list3)
I am getting output as :
["C:\\Users\\Desktop\\ABC\\001.py", "C:\\Users\\Desktop\\ABC\\001.xls", "C:\\Users\\Desktop\\ABC\\001.pdf"]
I am looking for output as :
["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
If you can use Python 3, pathlib can help you assemble your paths in a clearer way! If you're forced to use Python 2, you could bring in the library it's based off!
The double-backslash occurs and needs to be dealt with because Windows bizarrely chose to use \ instead of / as the path separator while it is ubiquitous as an escape character in many, especially C-derived languages. You can use / and it'll still work fine. You'll find need to escape spaces with \ when not using pathlib too.

get filenames in a directory without extension - Python [duplicate]

This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Closed 3 years ago.
I am trying to get the filenames in a directory without getting the extension. With my current code -
import os
path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = os.listdir(path)
print (files)
I end up with an output like so:
['img_8111.jpg', 'img_8120.jpg', 'img_8127.jpg', 'img_8128.jpg', 'img_8129.jpg', 'img_8130.jpg']
However I want the output to look more like so:
['img_8111', 'img_8120', 'img_8127', 'img_8128', 'img_8129', 'img_8130']
How can I make this happen?
You can use os's splitext.
import os
path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print (files)
Just a heads up: basename won't work for this. basename doesn't remove the extension.
Here are two options
import os
print(os.path.splitext("path_to_file")[0])
Or
from os.path import basename
print(basename("/a/b/c.txt"))

Path to a file without basename [duplicate]

This question already has answers here:
How do I get the parent directory in Python?
(21 answers)
Closed 1 year ago.
How can I get the path of a file without the file basename?
Something like /a/path/to/my/file.txt --> /a/path/to/my/
Tried with .split() without success.
Use os.path.dirname(filename).
You can import os
>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>>
(dirname, filename) = os.path.split(path)
Check subs of os.path
os.path.dirname('/test/one')
Since Python 3.4 you can use Pathlib.
from pathlib import Path
path = Path("/a/path/to/my/file.txt")
print(path.parent)

Categories

Resources