Python os.DirEntry.name属性
Python os模块的os.scandir()方法产生os.DirEntry对象,对应于指定路径给出的目录中的条目。os.DirEntry对象具有各种属性和方法,用于公开目录项的文件路径和其他文件属性。
os.DirEntry对象上的name属性用于获取条目的基本文件名,相对于os.scandir()方法中使用的path参数。
注意:os.DirEntry对象的目的是在迭代后被使用和扔掉,因为对象的属性和方法缓存了它们的值,再也不会重新获取值。如果文件的元数据已经被更改,或者如果自调用os.scandir()方法以来已经经过了很长时间。我们将得不到最新的信息。
os.DirEntry.name 语法
os.DirEntry.name
os.DirEntry.name 参数
None
返回值:该属性返回一个表示条目基本文件名的字符串值。
os.DirEntry.name 示例1
使用os.DirEntry.name属性
# Python program to explain os.DirEntry.name attribute
# importing os module
import os
# Directory to be scanned
# Current working directory
path = os.getcwd()
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
print("Base filename of all directory entry in '% s':" % path)
with os.scandir(path) as itr:
for entry in itr :
# Exclude the entry name
# starting with '.'
if not entry.name.startswith('.') :
# print entry's name
print(entry.name)
输出:
Base filename of all directory entry in '/home/ihritik':
Public
Desktop
R
foo.txt
graph.cpp
tree.cpp
Pictures
abc.py
file.txt
Videos
images
Downloads
GeeksforGeeks
Music
Documents
os.DirEntry.name 示例2
使用os.DirEntry.name()属性
# Python program to explain os.DirEntry.name attribute
# importing os module
import os
# Directory to be scanned
# Current working directory
path = os.getcwd()
# Using os.scandir() method
# scan the specified directory
# and yield os.DirEntry object
# for each file and sub-directory
print("All files and directory whose name starts with letter 'D' in '% s'" % path)
with os.scandir(path) as itr:
for entry in itr :
# Check if directory entry name
# starts with letter 'D'
if entry.name.startswith('D') :
# print entry's name
print(entry.name)
输出:
All files and directory whose name starts with letter 'D' in '/home/ihritik':
Desktop
Documents
Downloads
参考资料:https:/ docs.python.org/ library/os.html#os.DirEntry.name