0

I am trying to save multiple FTP files downloaded from a server to a subdirectory. I can pull and save the files but it saves to the current working directory.

When I execute the code below, I get an error "TypeError: a bytes-like object is required, not 'str'"

The full traceback is

Traceback (most recent call last):
  File "c:\Users\me\pyfanuc\Scripts\connectfanuc.py", line 37, in <module>        
    ftp.retrbinary(f"RETR {f}", file.write(logs))
                                ^^^^^^^^^^^^^^^^
TypeError: a bytes-like object is required, not 'str'

I am expecting to see the two 'filenames' inside of the folder 'FTPLogs' that I created.

Essentially what I'd like to do is get all of the filenames available and save each one individually a folder. Any help would be greatly appreciated.

from contextlib import ExitStack
import ftplib
import datetime
import sys
import filetype
import os.path

hostname = '172.22.xx.xx'
username = 'anonymous'
password = 'anonymous'

try:
        ftp.quit()
except:
        pass
    
# Connect to FTP Server [Fanuc]
ftp = ftplib.FTP(hostname, username, password)

# ****** Force UTF-8 encoding
ftp.encoding="utf-8"

# ****** Retrieve List of Available Directiories
dir = ftp.nlst()

# ****** File name [make a list, pull from list]
filenames = ['curpos.dg', 'errall.ls']
#filenames = ftp.nlst()
save_path = 'C:\\Users\\me\\pyfanuc\\FTPlogs'

for f in filenames:
    logs = os.path.join(save_path,f) 
    with open(f, "wb") as file:
        # Command for downloading file "RETR filenames"
        ftp.retrbinary(f"RETR {f}", file.write(logs))

    #file = open(filenames, "r")
    #print('File Content:', file.read())

ftp.quit()

0 Answers0