Hi everybody!

For the last five days I`m working on a project and I see only python syntax in from of my eyes.
I have a small problem and I got stuck.

I have a string like this : file = "E:\xxx\yyy.txt" and I want to format it in order to get only the file name - file = "yyy.txt".

How can I do that?


Thanks!

Recommended Answers

All 6 Replies

file = file.rsplit("\\")[-1]

Thanks for your help!

Hey,

The code bsod1 gave you is much shorter dan mine but I want to give it anyway because it might help you out with future 'problems'...

import os

fpath = 'C:\\tmp\\Test\\TestText.txt'

(filedir, filename) = os.path.split(fpath)
(shortname,extension) = os.path.splitext(filename)

print filedir
print filename
print shortname
print extension

Hey,

The code bsod1 gave you is much shorter dan mine but I want to give it anyway because it might help you out with future 'problems'...

import os

fpath = 'C:\\tmp\\Test\\TestText.txt'

(filedir, filename) = os.path.split(fpath)
(shortname,extension) = os.path.splitext(filename)

print filedir
print filename
print shortname
print extension

Thanks!

Just a note:
avoid using 'file' for an identifier, since it is a built-in Python function.

You can print out all builtin Python 'functions' in sorted order this way ...

print( '\n'.join(sorted(dir(__builtins__), key=str.lower)))

Avoid using any of those names for your variables, or you will get conflicts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.