简体   繁体   English

如何在目录中找到文件名?

[英]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 ? 例如,在路径C:\\Users\\Username\\filename.txt ,如何打印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

\\分隔路径并获得最后一个元素(应该是文件名):

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

The best way to do this intelligently is with the os module. 明智地执行此操作的最佳方法是使用os模块。


import os 

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

>f_name
'filename.txt'

Try this: 尝试这个:

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

method 1, you need to know the length of the filename: 方法1,您需要知道文件名的长度:

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

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

method 2, using os.path.split: 方法2,使用os.path.split:

import os

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

method 3, using str.split. 方法3,使用str.split。 You need to make sure the path is seperated by '/': 您需要确保路径以'/'分隔:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM