繁体   English   中英

以缩写名称搜索一个文件(从列表中)作为输入

[英]Search one file (from list) with shortened name as input

下面的代码连接到我的 FTP 服务器并查找文件; 这些文件在名称的开头有时间戳并添加了文件名,例如“timestamp+name.txt”。 这些时间戳通常有 16 个字符,如下所示:

在此处输入图像描述

我试图让这个“搜索器”通过忽略时间戳来搜索文件,所以它实际上应该寻找“FTPtest.txt”。 我正在为 for 循环的使用而苦苦挣扎。 我做了很少的代码来测试:

files = ftp.nlst()
for x in files:
    print(x[16:])

这确实列出了名称被截断的文件,但我不知道如何在我的代码中使用它。 下面的代码完全可以正常工作,但现在我需要修改它。 在输入中,用户只写短文件名('FTPtest.txt')而不是全名,但它搜索准确的输入,忽略时间戳。 这里的时间戳总是 16 个字符,但名称可以与 FTPtest.txt 不同。 下面是我的代码:

from ftplib import FTP
from ftplib import FTP, error_perm

def repeat():
    ftp = FTP(host="ip")
    ftp.login(user='user', passwd='pass')
    file_name = str(input('>>> What is name of your file? \n'))
  
    try:
        ftp.cwd('/test')
        if file_name in ftp.nlst():
            print("+++File found!+++")
        else:
            print("---File not found---")
    except error_perm:
            print("File does not exist")
    ftp.quit()
while True:
   repeat()

我的理解是,您只想查看文件是否完全匹配,不包括前 16 个字符,所以执行类似的操作。

    try:
        ftp.cwd('/test')
        if file_name in [f[16:] for f inftp.nlst()]:
            print("+++File found!+++")
        else:
            print("---File not found---")
    except error_perm:
            print("File does not exist")

应该管用。 请注意,这不是最有效的,因为它在列表中迭代了两次,但它很简洁。

暂无
暂无

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

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