gpt4 book ai didi

python - 如何使用 Python ftplib 获取 FTP 文件的修改时间

转载 作者:太空狗 更新时间:2023-10-29 18:26:26 30 4
gpt4 key购买 nike

我正在尝试使用 Python 将 CSV 文件加载到 Amazon S3。我需要知道 CSV 文件的修改时间。我正在使用 ftplib 将 FTP 与 Python (2.7) 连接。

最佳答案

MLST 或 MDTM

虽然您可以使用 MLSTMDTM 命令通过 FTP 检索单个文件的时间戳,但 ftplib 均不支持。

当然,您可以使用FTP.voidcmd 自行实现MLSTMDTM .

详情请引用RFC 3659 ,尤其是:

MDTM 的一个简单示例:

from ftplib import FTP
from dateutil import parser

# ... (connection to FTP)

timestamp = ftp.voidcmd("MDTM /remote/path/file.txt")[4:].strip()

time = parser.parse(timestamp)

print(time)

MLSD

ftplib 库明确支持的唯一可以返回标准化文件时间戳的命令是 MLSD via FTP.mlsd method .尽管只有当您想要检索更多文件的时间戳时,它的使用才有意义。

  • 使用 MLSD 检索完整的目录列表
  • 在返回的集合中搜索您想要的文件
  • 检索修改事实
  • 按照规范解析,YYYYMMDDHHMMSS[.sss]

有关详细信息,请再次引用 RFC 3659,特别是:

from ftplib import FTP
from dateutil import parser

# ... (connection to FTP)

files = ftp.mlsd("/remote/path")

for file in files:
name = file[0]
timestamp = file[1]['modify']
time = parser.parse(timestamp)
print(name + ' - ' + str(time))

请注意,MLSTMLSDMDTM 返回的时间均为 UTC(除非服务器损坏)。因此,您可能需要根据您本地的时区更正它们。

再次引用 RFC 3659 2.3. Times部分:

Time values are always represented in UTC (GMT), and in the Gregoriancalendar regardless of what calendar may have been in use at the dateand time indicated at the location of the server-PI.


列表

如果 FTP 服务器不支持 MLSTMLSDMDTM 中的任何一个,您所能做的就是使用过时的 LIST 命令。这涉及解析它返回的专有列表。

一个常见的 *nix list 是这样的:

-rw-r--r-- 1 user group           4467 Mar 27  2018 file1.zip
-rw-r--r-- 1 user group 124529 Jun 18 15:31 file2.zip

对于这样的列表,此代码将执行:

from ftplib import FTP
from dateutil import parser

# ... (connection to FTP)

lines = []
ftp.dir("/remote/path", lines.append)

for line in lines:
tokens = line.split(maxsplit = 9)
name = tokens[8]
time_str = tokens[5] + " " + tokens[6] + " " + tokens[7]
time = parser.parse(time_str)
print(name + ' - ' + str(time))

查找最新文件

另见 Python FTP get the most recent file by date .

关于python - 如何使用 Python ftplib 获取 FTP 文件的修改时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026709/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com