Search code examples
pythonpython-2.7ftpwavftplib

How to read the header of WAV file from FTP directly without downloading whole file in Python?


I want to read the WAV file (which is in my FTP server) directly from FTP server without downloading it into my PC in Python. Is it possible and if yes the how?

I tried this solution Read a file in buffer from ftp python but it didn't work. I have .wav audio file. I want to read the file and get details from that .wav file like file size, byte rate, etc.

My code which in which I was able to read the WAV files locally:

import struct

from ftplib import FTP

global ftp
ftp = FTP('****', user='user-****', passwd='********')

fin = open("C3.WAV", "rb") 
chunkID = fin.read(4) 
print("ChunkID=", chunkID)

chunkSizeString = fin.read(4) # Total Size of File in Bytes - 8 Bytes
chunkSize = struct.unpack('I', chunkSizeString) # 'I' Format is to to treat the 4 bytes as unsigned 32-bit inter
totalSize = chunkSize[0]+8 # The subscript is used because struct unpack returns everything as tuple
print("TotalSize=", totalSize)

Solution

  • For a quick implementation, you can make use of my FtpFile class from:
    Get files names inside a zip file on FTP server without downloading whole archive

    ftp = FTP(...)
    fin = FtpFile(ftp, "C3.WAV")
    # The rest of the code is the same
    

    The code is bit inefficient though, as each fin.read will open a new download data connection.


    For a more efficient implementation, just download whole header at once (I do not know WAV header structure, I'm downloading 10 KB here as an example):

    from io import BytesIO
    
    ftp = FTP(...)
    fin = BytesIO(FtpFile(ftp, "C3.WAV").read(10240))
    # The rest of the code is the same