Home > Enterprise >  remove specific file path for replacement of a new one
remove specific file path for replacement of a new one

Time:10-08

I have a list of strings that contain a file path per list that I need to replace without the file name itself being replaced. Below is an example of what I am starting with.

['/folder1/folder2/folder3/fileName.csv', '/folderA/folderB/fileNameDifferent.csv', '/folder/fileName2.xlsx']

I want to store all of the files in the same directory but keep the file names. I am looping through this with python right now. What would be the best replacement method to get an output like this below? Basically make the file path uniform without losing the original name of these files.

/newLocation/newfolder/fileName.csv,
/newLocation/newfolder/fileNameDifferent.csv
/newLocation/newfolder/fileName2.xlsx

CodePudding user response:

The main thing to know about here is the os.path subpackage. It has lots of neat functions for working with paths in a platform-agnostic way. os.path.basename gives you the final component of the path, the filename if it's a file path, or the name of the deepest directory if its a directory path. os.path.join is the preferred way to construct paths from component parts in a platform-agnostic way...generally much preferred to simple string concatenation.

import os

paths = ['/folder1/folder2/folder3/fileName.csv', '/folderA/folderB/fileNameDifferent.csv', '/folder/fileName2.xlsx']

for path in paths:
    newpath = os.path.join('/newLocation/newfolder', os.path.basename(path))
    print(newpath)

Result:

/newLocation/newfolder/fileName.csv
/newLocation/newfolder/fileNameDifferent.csv
/newLocation/newfolder/fileName2.xlsx
  • Related