1

I have some folders in C:\Users\Documents\Datas, whose names are A, B, C.

  • Inside folder A: RE_20.csv ; RE_23.csv ; RE_25.csv
  • Inside folder B: DF_41.csv ; DF_46.csv ; RE_47.csv
  • Inside folder C: VN_81.csv ; VN_82.csv ; VN_89.csv

I want to replace just a part of .csv files with the name of its folder correspondent. I want to get:

  • Inside folder A: A_20.csv ; A_23.csv ; A_25.csv
  • Inside folder B: B_41.csv ; B_46.csv ; B_47.csv
  • Inside folder C: C_81.csv ; C_82.csv ; C_89.csv

1 Answer 1

1

The pathlib library was born for this sort of path manipulation.

Try this:

from pathlib import Path import re paths=Path('C:\\Users\\Documents\\Datas').glob('*/*.csv') for path in paths: new_path = path.parent/re.sub('.+_',path.parent.name+'_',path.name) print(path,'->',new_path) path.replace(new_path) 
Sign up to request clarification or add additional context in comments.

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.