Home > Enterprise >  Remove file name and extension from path and just keep path
Remove file name and extension from path and just keep path

Time:08-03

Hi I have a string like this which will be dynamic and can be in following combinations.

'new/file.csv'
'new/mainfolder/file.csv'
'new/mainfolder/subfolder/file.csv'
'new/mainfolder/subfolder/secondsubfolder/file.csv'

Something like these. In any case I just want this string in 2 parts like path and filename. Path will not consist of file name for example.

End result expected

    'new'
    'new/mainfolder'
    'new/mainfolder/subfolder'
    'new/mainfolder/subfolder/secondsubfolder'

Till now tried many things included

path = 'new/mainfolder/file.csv'
final_path = path.split('/', 1)[-1]

And rstrip() but nothing worked till now.

CodePudding user response:

You can use pathlib for this.

For example,

>>>import pathlib
>>>path = pathlib.Path('new/mainfolder/file.csv')
>>>path.name
'file.csv'
>>>str(path.parent)
'new/mainfolder'

CodePudding user response:

  input  = ['new/file.csv',
'new/mainfolder/file.csv',
'new/mainfolder/subfolder/file.csv',
'new/mainfolder/subfolder/secondsubfolder/file.csv']

output = []
for i in input:
  i = i.split("/")[:-1]
  i = "/".join(i)
  output.append(i)

print(output)

Output:

['new', 'new/mainfolder', 'new/mainfolder/subfolder', 'new/mainfolder/subfolder/secondsubfolder']

CodePudding user response:

An option to pathlib is os

import os
fullPath = 'new/mainfolder/file.csv'
parent = os.path.dirname(fullPath) # get path only
file = os.path.basename(fullPath) # get file name

print (parent)

Output:

new/mainfolder

path.dirname:

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split(). Source: https://docs.python.org/3.3/library/os.path.html#os.path.dirname

path.basename:

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string (''). Source: https://docs.python.org/3.3/library/os.path.html#os.path.basename

CodePudding user response:

you almost got it, just use rsplit, like this:

path = 'new/mainfolder/file.csv'

file_path, file_name = path.rsplit('/', 1)

print(f'{file_path=}\n{file_name=}')
'''
file_path='new/mainfolder'
file_name='file.csv'
  • Related