1

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 ...

2
  • 2
    Split the string on /. Replace. Join back. Commented Aug 11, 2022 at 21:48
  • Or use pathlib. Commented Aug 11, 2022 at 21:49

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I updated it that it's independent of the file name and type.
0

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.