求推荐类似pathlib的Python远程文件浏览库(支持获取最新文件)
可用的Python库推荐
1. fs(Filesystem Abstraction Layer)
这是一套通用文件系统抽象库,若你的Web服务器支持WebDAV协议,它能实现和pathlib几乎一致的使用体验,像操作本地文件一样浏览远程目录、获取文件元数据(包括修改时间戳)。
示例代码:
from fs.webdavfs import WebDAVFS # 初始化远程WebDAV文件系统 fs = WebDAVFS("http://your-server-root-url", username="your-username", password="your-password") # 遍历根目录下的文件/文件夹 with fs.opendir("/") as dir: for item in dir.scandir(): if item.is_file: # 获取文件修改时间戳 mtime = fs.getinfo(item.name, namespaces=["details"]).modified print(f"文件: {item.name}, 修改时间: {mtime}") # 筛选最新文件 files = [] for item in fs.scandir("/"): if item.is_file: info = fs.getinfo(item.name, namespaces=["details"]) files.append((info.modified, item.name)) # 按时间戳排序取最新 latest_file = max(files, key=lambda x: x[0])[1] print(f"最新文件: {latest_file}")
注:需要Web服务器开启WebDAV支持,比如Apache的mod_dav模块、Nginx的dav_ext模块。
2. paramiko(针对SFTP服务器)
若你的Web服务器同时支持SFTP,paramiko可实现类pathlib的远程文件操作,能直接获取文件修改时间,轻松筛选最新文件。
示例代码:
import paramiko from stat import S_ISREG # 建立SFTP连接 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("your-server-host", username="your-username", password="your-password") sftp = ssh.open_sftp() # 遍历Web根目录 for entry in sftp.listdir_attr("/path-to-web-root"): if S_ISREG(entry.st_mode): # 获取修改时间戳 mtime = entry.st_mtime print(f"文件: {entry.filename}, 修改时间: {mtime}") # 筛选最新文件 file_list = [] for entry in sftp.listdir_attr("/path-to-web-root"): if S_ISREG(entry.st_mode): file_list.append((entry.st_mtime, entry.filename)) latest_file = max(file_list, key=lambda x: x[0])[1] print(f"最新文件: {latest_file}") # 关闭连接 sftp.close() ssh.close()
3. requests-fs(基于requests的文件系统封装)
这个库是requests的扩展,将远程HTTP目录封装成类pathlib的接口,会自动解析服务器返回的目录索引页面——你无需自己编写HTML爬取逻辑,完全符合你“无需爬取HTML”的需求。
示例代码:
from requests_fs import Filesystem fs = Filesystem("http://your-server-root-url") # 遍历目录 for path in fs.glob("*"): if path.is_file(): # 获取修改时间 mtime = path.stat().st_mtime print(f"文件: {path.name}, 修改时间: {mtime}") # 查找最新文件 files = [p for p in fs.glob("*") if p.is_file()] latest_file = max(files, key=lambda x: x.stat().st_mtime) print(f"最新文件: {latest_file.name}")
内容的提问来源于stack exchange,提问作者scorpion35
相关产品推荐
相关产品推荐

