[Python] File downloaded from FTP with Python ftplib is encoded incorrectly

Discussão em 'Python' iniciado por Stack, Fevereiro 7, 2025.

  1. Stack

    Stack Membro Participativo

    I'm retrieving a file from a NAS via FTP in two ways:


    1. with a .bat file where I have:

      a) ftp -s:C:\TEMP\runTheDownload.txt (The script calls the code from the txt)
      b) The .txt containing the following:

      open some.address.eu
      username
      password
      ascii

      quote "site SBDataconn=ANOTHER.ADD.RESS.HERE
      get 'THE.NAS.LOCATION.OF.THE.FILE' C:\TEMP\output.txt

    2. I have a Python code with above inputs where I use ftplib and the following code:

      with FTP(ftp_server) as ftp:
      ftp.login(ftp_user, ftp_password)
      print("Connected to FTP server.")

      # Set transfer mode to ASCII
      ftp.sendcmd("TYPE A")
      # print("Switched to ASCII mode.")

      # Execute the custom FTP command (quote)
      ftp.sendcmd('SITE SBDataconn=ANOTHER.ADD.RESS.HERE')
      print("Custom SITE command executed.")

      # Download the file
      with open(local_file, 'wb') as file_obj:
      # Write info to buffer
      ftp.retrbinary(
      f"RETR {remote_file}", file_obj.write)

    When I look at the output.txt from the first approach it gives me perfectly fine data like 001, abc, 2013230..., the Python output however gives me encoded returns like:


    \x7f\xf0\xf0\xf1\x7fk\x7f\xf0\xf0\xf0\xf0\xf1\xf0\xf2\xf4\xf9\x7fk\x7f\xf0\xf0\xf0\xf0\xf0\xf0\xf0\xf0\xf0\x7fk\x7fN\xf0\x7fk\x7f\xf0\xf4\x7fk\x7f\xf0\xf0\x7fk\x7f@@@@@@@@@@\x7fk\x7f\xd6\xd7\xc3\xe4\xe2\xc5\xd9@\x7fk\x7f\x81\xa4\xa3\x96\x94\x81\xa3\x89\xa2\x83\x88\x85@\xc5\x89\x95\xa2\xa3\xa4\x86\xa4\x95\x87@`@\xf1K\xf7K\xf2@@@@@@@@@
    ​

    I'm wondering what I'm missing in my Python code to transform it nicely like it is being done with the .bat file.

    I tried decoding it in different ways, but it never gave me back anything that looked remotely like the proper result. Best thing I got was with "ISO-8859-1" decoding which led to


    \x7fððñ\x7fk\x7fððððñðòôù\x7fk\x7fððððððððð...
    ​

    I'm grateful for any advice on what kind of decoding I would need to apply in Python to get the Same result as in the .bat file.

    Continue reading...

Compartilhe esta Página