Get substring from end to certain character in python [duplicate] - python

This question already has answers here:
How to get only the last part of a path in Python?
(10 answers)
Closed 4 years ago.
I want to get the substring from a path from the end to a certain character, take for example the following path:
my_path = "/home/Desktop/file.txt"
My intention is to do something like:
my_path.substring(end,"/")
So I can get the name of the file that is located between the end of the string and the character "/", in this case "file.txt"

The easiest approach, IMHO, would be to split the string:
filename = my_path.split('/')[-1]

use the os.path.basename for this
In [1]: import os
In [2]: os.path.basename('/home/Desktop/file.txt')
Out[2]: 'file.txt'

Related

Removing two non printable characters from a string in python [duplicate]

This question already has answers here:
Removing control characters from a string in python
(9 answers)
Closed 2 years ago.
I am getting a text like below by reading a word file
Exe Command\r\x07
My desired text is
Exe Command
I tried this solution but it gives me
Exe Command\r
How can i remove 2 any backslash characters? I would like a speed friendly solution because I have thousands of inputs like this.
You can use replace() method twice.
In [1]: myStr.replace("\r", "").replace("\x07", "")
Out[1]: 'Exe Command'
If this isn't working, you can try using raw string
In [1]: myStr.replace(r"\r", "").replace(r"\x07", "")
Out[1]: 'Exe Command'
EDIT: As per comment, for removing any of those control characters, use this post's solution.
import unicodedata
def remove_control_characters(s):
return "".join(ch for ch in s if unicodedata.category(ch)[0]!="C")
All credits for this solution goes to Alex Quinn.

How to extract the filename from a string using regular expression [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Extract file name with a regular expression
(3 answers)
Get Filename Without Extension in Python
(6 answers)
Extracting extension from filename in Python
(33 answers)
Regex: Get Filename Without Extension in One Shot?
(10 answers)
Closed 3 years ago.
I am new in the regular expression and trying to extract the file name from a string which is basically a file path.
string = "input_new/survey/argentina-attributes.csv"
string_required = argentina-attributes
i know i can do this by below code.
string.split('/')[2].split('.')[0]
but I am looking to do this by using regular expression so if in future the formate of the path changes(input_new/survey/path/path/argentina-attributes.csv) should not affect the output.
i know kind of similar question asked before but I am looking for a pattern which will work for my use case.
Try this,
>>> import re
>>> string = "input_new/survey/argentina-attributes.csv"
Output:
>>> re.findall(r'[^\/]+(?=\.)',string) # or re.findall(r'([^\/]+)\.',string)
['argentina-attributes']
Referred from here
Try this:
string = "input_new/survey/argentina-attributes.csv"
new_string = string.split('/')[-1].split('.')[0]
print(new_string)

Getting "TypeError: string indices must be integers" in python [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
How can I extract the folder path from file path in Python?
(7 answers)
Closed 4 years ago.
I tried imitating my code in simple steps on python prompt:
>>> path="D:/workspace/a/b\\c\\d.txt"
>>> path[0,18]
But it gives me following error:
TypeError: string indices must be integers
I wanted to retrieve only directory as path. That is, I want to strip away the file name: D:/workspace/a/b\\c
Why I am getting this error?
path[0,18] should be path[0:18] or path[:18]
Even better (will work not matter what length the parent directory is):
import os
os.path.split(path)[0]
You can replace with regex as well
import re
result = re.sub(r'\\[a-z]*.txt', '', path)
path="some/again_a_dir/file.txt"
print(path[0:16])
When we want to get a range of letters from the string, we should use ":" to define the range. path[0:16] means get items from the 1st element to 17th element of your string.

Use 2 string replace without the first having effect on the second [duplicate]

This question already has answers here:
How to replace two things at once in a string?
(6 answers)
Closed 4 years ago.
Because of this answer, it might be necessary to do this:
path = r"D:\Temp\abc[def]\ # (i have many others to process)
path = path.replace('[', '[[]').replace(']', '[]]')
# now we can use glob here with path
However, the first replace gets mixed up with the second replace, and the result is not what is expected, i.e. D:\Temp\abc[[]def[]]\.
The only solution I found is to use a temporary character ~ to avoid the 2 replace to be mixed up with each other:
path = path.replace('[', '[[~').replace(']', '[]]').replace('~', ']')
Is there a nice way to use 2 replacements without the first having effect on the second?
You don't need to replace ].
Special characters to replace are only '?', '*' and '[', and are handled by glob.escape.
>>> print(glob.escape(path))
D:\Temp\abc[[]def]\

Opening files with the name of a variable [duplicate]

This question already has answers here:
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 4 years ago.
I am using a Markov chain. When the chain arrives at a particular state, two files (a .png and an .mp3) need to open.
s is the current state of the chain, an integer from 1-59.
I can't seem to find how to open the file with the same number as 's'.
I'm sure it has something to do with %str formatting, but I can't seem to implement it.
img = Image.open('/.../.../s.png')
img.show()
You should use the following line in your code:
img = Image.open('/.../.../{0}.png'.format(s))
You can format a string using a variable like this
>>> s = 10
>>> '/path/to/file/{}.png'.format(s)
'/path/to/file/10.png'

Categories