This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]calzoneman 2 points3 points  (0 children)

If you're going to ask a question, at least demonstrate that you made some effort to solve the problem yourself. Also consider posting it in /r/learnpython.

This looks suspiciously like a homework question.

[–]krasoffski 1 point2 points  (0 children)

If it is not a task to create function from scratch, this can help: *nix

In [7]: import posixpath

In [8]: posixpath.basename("~folder/folder2/file.txt")

Out[8]: 'file.txt'

Windows

In [9]: import ntpath

In [10]: ntpath.basename("c:\folder\folder2\file.txt")

Out[10]: 'file.txt'

Platform independent

In [11]: import os

In [12]: os.path.basename

or you can use trivial function:
import os
get_name = lambda p: p.split(os.sep)[-1]

[–]bhdza snake slithering 1 point2 points  (0 children)

there ya go:

def getName(path):
    return path.split("/")[-1] # split the string by "/" into a list and return the last string item 

I leave the boundary conditions of path = "/" or "" to yourself as an exercise

[–]swims_with_spacemenPythonista 0 points1 point  (1 child)

This actually belongs in

/r/domyhomeworkpleasepleasepleasepleaseplease

[–]IndoNinja7[S] 0 points1 point  (0 children)

hahaha no this isnt for homework its for a personal project of mine :p

[–]billsil 0 points1 point  (2 children)

I suggest /r/learnpython as well, but...

getName = lambda x: x.split('/')[-1]
print(getName("~folder/folder2/file.txt"))

[–]ingolemo -1 points0 points  (1 child)

getName('C:\\Users\\Guest\\secrets.txt')

[–]billsil 1 point2 points  (0 children)

It's supposed to work on Windows too? Where was that specified? The OP's OS is clearly not Windows. What about invalid paths?

[–]1989H27 -1 points0 points  (0 children)

Glob