Home > Enterprise >  Python ftplib two issues
Python ftplib two issues

Time:12-16

I have this code to access and download a file via python.

# Import Module
import ftplib
 
# Fill Required Information
HOSTNAME = "xxx"
USERNAME = "xxx"
PASSWORD = "xxx"
 
# Connect FTP Server
ftp_server = ftplib.FTP(HOSTNAME, USERNAME, PASSWORD)
 
# force UTF-8 encoding
ftp_server.encoding = "utf-8"
 
# Enter File Name with Extension
filename = "gfg.txt"
 
# Write file in binary mode
with open(filename, "wb") as file:
    # Command for Downloading the file "RETR filename"
    ftp_server.retrbinary(f"RETR {filename}", file.write)
 
# Get list of files
ftp_server.dir()
 
# Display the content of downloaded file
file= open(filename, "r")
print('File Content:', file.read())
 
# Close the Connection
ftp_server.quit()

Now I have these 2 questions.

1.How can I download a file inside the ftp that is inside a directory. It can download I suppose the script but just from root how can I modify the code to access a subdirectory inside the FTP

2.-I tried to download a file in .zip from root of a FTP and I received the next error message:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 12: character maps to <undefined>

What could be the problem in the code?

Thank you

I just tried the code like it is. I did not change anything yet.

CodePudding user response:

(1.) inside a directory

Use / forward slashes, rather than \ backwhacks:

filename = "some/remote/directory/gfg.txt"

Or issue an FTP cd command to chdir to the remote directory.


(2.) UnicodeDecodeError

You mentioned "download", but that part looks suitably binary. I assume the error occurred when you read back the local copy. Use rb binary mode:

file= open(filename, "rb")
content = file.read()

That will retrieve binary content bytes, which won't necessarily print nicely. But you can uncompress / unzip them.


Consider using ftptool.

  • Related