如何直接从FTP读取WAV文件的标题而无需在Python中下载整个文件?

问题描述 投票:2回答:1

我想直接从FTP服务器读取WAV文件(在我的FTP服务器中),而不是用Python下载到我的PC中。是否可能,如果是,如何?

我试过这个解决方案Read a file in buffer from ftp python但它没有用。我有.wav音频文件。我想读取该文件并从该.wav文件中获取详细信息,如文件大小,字节速率等。

我能在本地读取WAV文件的代码:

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)
python python-2.7 ftp wav ftplib
1个回答
0
投票

为了快速实现,您可以使用我的FtpFile类: 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

但是代码效率低,因为每个fin.read都会打开一个新的下载数据连接。


为了更有效的实现,只需立即下载整个标头(我不知道WAV标头结构,我在这里下载10 KB作为示例):

from io import BytesIO

ftp = FTP(...)
fin = BytesIO(FtpFile(ftp, "C3.WAV").read(10240))
# The rest of the code is the same
© www.soinside.com 2019 - 2024. All rights reserved.