newbiee
newbiee

Reputation: 113

replace specific chunk of string when string is path

hi I have a string like this:

path = "/level1/level2/level3/file.csv"

I want to do a operation in 2 steps like first is want to replace file name for example

path = "/level1/level2/level3/file_1.csv"

and in some cases only folder which is 2nd last from end like this

   path = "/level1/level2/level3_1/file.csv"

so what will be best way to do this ? currently I am doing like this

path.replace('level3','level3_1')

but It got failed when there is same name exist somewhere else in string ...

Upvotes: 1

Views: 265

Answers (2)

SergFSM
SergFSM

Reputation: 1491

a different use of regexp could look like this:

from re import sub

path = "/level1/level2/level3/file.csv"

file_suff = '_1' # '' - for no replacement
dir_suff = '_1'  # '' - for no replacement

sub(r'(^.*)/(\w+)(\.\w+$)',fr'\1{dir_suff}/\2{file_suff}\3',path)

>>> out
'/level1/level2/level3_1/file_1.csv'

Upvotes: 0

codeofandrin
codeofandrin

Reputation: 1547

Use regex to avoid errors with replace() when 2 same directories are in path.

File

import re

path = "/level1/level2/level3/file.csv"

# get file
file = re.search("[A-Za-z]+\.[A-Za-z]+", path).group(0).split(".")
file_name = file[0]
file_type = file[1]
new_path = path.replace(f"{file_name}.{file_type}", "file_2.txt")

print(new_path)

Output

/level1/level2/level3/file_2.txt

Last folder

import re

path = "/level1/level2/level3/file.csv"

# search for file
file = re.search("[A-Za-z]+\.[A-Za-z]+", path).group(0)

# to make sure it's last folder, get it with the file
level3_folder = re.search(f"[A-Za-z0-9_ -]+/{file}", path).group(0)

# remove the file from folder to rename it
level3_folder = level3_folder.replace(f"/{file}", "")

# rename it
new_path = path.replace(f"{level3_folder}/{file}", f"level3_1/{file}")

print(new_path)

Output

/level1/level2/level3_1/file.csv

Upvotes: 1

Related Questions