TheRealTengri
TheRealTengri

Reputation: 1361

How can I find the file name in a directory?

For example, in the path C:\Users\Username\filename.txt, how would I print filename.txt?

Here is an example of a code:

>>> x = input("Enter file path: ")
>>> Enter file path: C:\Users\Username\filename.txt
# Now print filename.txt because that is the name of the file in the variable x

Upvotes: 0

Views: 266

Answers (4)

ToughMind
ToughMind

Reputation: 1009

method 1, you need to know the length of the filename:

path = "C:\Users\Username\filename.txt"

file = path[-12:] # ===> filename.txt

method 2, using os.path.split:

import os

file = os.path.split(path)[1]

method 3, using str.split. You need to make sure the path is seperated by '/':

file = path.split('/')[-1]

Upvotes: 0

Robert Kearns
Robert Kearns

Reputation: 1706

The best way to do this intelligently is with the os module.


import os 

Path = 'C:\Users\Username\filename.txt'
f_path, f_name = os.path.split(Path)

>f_name
'filename.txt'

Upvotes: 1

Djaouad
Djaouad

Reputation: 22766

Split the path by \ and get the last element (which is supposed to be the filename):

print(x.split('\\')[-1])  #  ==>  filename.txt

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71560

Try this:

x = input("Enter file path: ")
with open(x, 'r') as f:
    print(f.read())

Upvotes: 0

Related Questions