How to replace a sentence in line of string address? - python

I need help replacing a part of string on a list of file's address location.
The file address looks like this :
/SfSNet/Images_mask/10_face.png
and I need to change it into something like this
/SfSNet/Images_mask/10_mask.png
I know it is possible to count the index since the front string are the same but it will be annoying in case I want to run the code on other PC. I read something about regex but it isn't clear for me. So maybe if someone can help me with this or have any other solution will be appreciated, thank you

Assuming the structure of all file names is as the above, you could use re.sub as:
s = '/SfSNet/Images_mask/10_face.png'
s.replace('_face.png', '_mask.png')
# '/SfSNet/Images_mask/10_mask.png'

If a simple str.replace lacks generality1, consider doing operations like this is with os.path.
>>> import os.path
>>>
>>> s = '/SfSNet/Images_mask/10_face.png'
>>> folder, file = os.path.split(s) # ('/SfSNet/Images_mask', '10_face.png')
>>> name, ext = os.path.splitext(file) # ('10_face', '.png')
>>> new_name = '{}_{}{}'.format(name.rsplit('_', 1)[0], 'mask', ext)
>>> os.path.join(folder, new_name)
'/SfSNet/Images_mask/10_mask.png'
1 For example, if you want to preserve the extension name without hardcoding it or if the substring you want to replace might appear in the directory name itself.

Related

Python string alphabet removal?

So in my program, I am reading in files and processing them.
My output should say just the file name and then display some data
When I am looping through files and printing output by their name and data,
it displays for example: myfile.txt. I don't want the .txt part. just myfile.
how can I remove the .txt from the end of this string?
The best way to do it is in the example
import os
filename = 'myfile.txt'
print(filename)
print(os.path.splitext(filename))
print(os.path.splitext(filename)[0])
More info about this very useful builtin module
https://docs.python.org/3.8/library/os.path.html
The answers given are totally right, but if you have other possible extensions, or don't want to import anything, try this:
name = file_name.rsplit(".", 1)[0]
You can use pathlib.Path which has a stem attribute that returns the filename without the suffix.
>>> from pathlib import Path
>>> Path('myfile.txt').stem
'myfile'
Well if you only have .txt files you can do this
file_name = "myfile.txt"
file_name.replace('.txt', '')
This uses the built in replace functionality. You can find more info on it here!

Remove a string (filename) from a bigger string (the whole path)

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

python:extract certain part of string

I have a string from which I would like to extract certain part. The string looks like :
E:/test/my_code/content/dir/disp_temp_2.hgx
This is a path on a machine for a specific file with extension hgx
I would exactly like to capture "disp_temp_2". The problem is that I used strip function, does not work for me correctly as there are many '/'. Another problem is that, that the above location will change always on the computer.
Is there any method so that I can capture the exact string between the last '/' and '.'
My code looks like:
path = path.split('.')
.. now I cannot split based on the last '/'.
Any ideas how to do this?
Thanks
Use the os.path module:
import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]
Python comes with the os.path module, which gives you much better tools for handling paths and filenames:
>>> import os.path
>>> p = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> head, tail = os.path.split(p)
>>> tail
'disp_temp_2.hgx'
>>> os.path.splitext(tail)
('disp_temp_2', '.hgx')
Standard libs are cool:
>>> from os import path
>>> f = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> path.split(f)[1].rsplit('.', 1)[0]
'disp_temp_2'
Try this:
path=path.rsplit('/',1)[1].split('.')[0]
path = path.split('/')[-1].split('.')[0] works.
You can use the split on the other part :
path = path.split('/')[-1].split('.')[0]

Get Filename Without Extension in Python

If I have a filename like one of these:
1.1.1.1.1.jpg
1.1.jpg
1.jpg
How could I get only the filename, without the extension? Would a regex be appropriate?
In most cases, you shouldn't use a regex for that.
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc correctly by keeping the whole name.
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')
You can use stem method to get file name.
Here is an example:
from pathlib import Path
p = Path(r"\\some_directory\subdirectory\my_file.txt")
print(p.stem)
# my_file
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
No need for regex. os.path.splitext is your friend:
os.path.splitext('1.1.1.jpg')
>>> ('1.1.1', '.jpg')
One can also use the string slicing.
>>> "1.1.1.1.1.jpg"[:-len(".jpg")]
'1.1.1.1.1'

Renaming multiple files in python

I wanted to know what is the easiest way to rename multiple files using re module in python if at all it is possible.
In my directory their are 25 files all with the file names in the format ' A unique name followed by 20 same characters.mkv '
What I wanted was to delete all the 20 characters.
How can I do this using Python if at all it is possible :)
To get the new name:
>>> re.sub(r'.{20}(.mkv)', r'\1', 'unique12345678901234567890.mkv')
'unique.mkv'
Or without regex:
>>> 'unique12345678901234567890.mkv'[:-24] + '.mkv'
'unique.mkv'
To rename the file use os.rename(old, new): http://docs.python.org/library/os.html#os.rename
To get a list of the files to rename use glob.glob('*.mkv'): http://docs.python.org/library/glob.html#glob.glob
Putting that all together we get:
for filename in glob.glob('*.mkv'):
if len(filename) > 24:
os.rename(filename, filename[:-24] + '.mkv'
Since you are cutting out a specific number of characters from an easily identified point in the string, the re module is somewhat overkill. You can prepare the new filename as:
new_name = old_name.rsplit('.', 1)[0][:-20] + '.mkv'
To find the files, look up os.listdir (or, if you want to look into directories recursively, os.walk), and to rename them, see os.rename.
The re module would be useful if there are other .mkv's in the directory that you don't want to rename, so that you need to do more careful checking to identify the "target" filenames.
Use glob to find the filenames, slice the strings, and use os.rename() to rename them.
Something like:
>>> import os
>>> doIt = False
>>> for filename in ( x for x in os.listdir('.') if x.endswith('.mvk')):
... newname = filename[:-24] + filename[-4:]
... if doIt:
... os.rename(filename,newname)
... print "Renaming {0} to {1}".format(filename,newname)
... else:
... print "Would rename {0} to {1}".format(filename,newname)
...
When manipulating files, always have a dryrun. Change doIt to True, to actually move the files.
You need to use glob and os.rename. The rest if for you to figure it out!
And yes, this is entirely possible and easy to do in Python.

Categories