我正在尝试使用 python 2.7 os
和 glob
模块将最新的文件添加到目录中。
import os
import glob
path = "files/"
newestFile = max(glob.iglob(path + '*.txt'), key=os.path.getctime)
print newestFile
当我打印 newestFile
变量时,我得到了包含的路径,即
files\file.txt
我只想要文件名
,但我的.txt
文件和.py
脚本不在同一目录中。文本文件位于 files 目录下的下一个目录中。如何引用该目录并获取添加到该目录的最新 .txt
文件。
最佳答案
您可以使用os.path.basename
来获取文件名:
newestFile = os.path.basename(max(glob.iglob(path + '*.txt'), key=os.path.getctime))
os.path.getctime
将需要完整路径,因此无论如何您都必须使用完整路径。
关于python - glob.iglob 从文件名中删除路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30943502/