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

Question:

Code below is connecting to my FTPserver and looks for file; these files have timestamps at start of name and added filename, like ‘timestamp+name.txt’. Those timestamps usually have 16 characters, look below:

enter image description here

I’m trying to make this "searcher" to search files by ignoring timestamps, so it should look for ‘FTPtest.txt’ actually. I’m struggling with for loop usage. I did little code to test:

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

This indeed lists files with cutted names but I dont know how to make use of it in my code. This code below is fully working and doing it’s job, but now I need to modify it. In input user writes only short filename (‘FTPtest.txt’) and not full name, but it searches for exact input, ignoring timestamps. Here are just always 16 characters in timestamp, but the name can be different than FTPtest.txt. Below is my code:

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()
Asked By: michalb93

||

Answers:

My understanding is that you just want to see if there is a exact match by file excluding the first 16 characters so doing something like.

    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")

Should work. Note this is not the most efficient as it iterates twice over the list but it is concise.

Answered By: Carlos Gonzalez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.