首页 > 解决方案 > 如何直接从 FTP 读取 WAV 文件的标题而不用 Python 下载整个文件?

问题描述

我想直接从 FTP 服务器读取 WAV 文件(在我的 FTP 服务器中),而不用 Python 将它下载到我的 PC 中。有可能吗?如果可以,怎么做?

我试过这个解决方案从 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)

标签: pythonpython-2.7ftpwavftplib

解决方案


为了快速实现,您可以使用我的FtpFile课程:
Get files names inside a zip file on FTP server without download entire 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

推荐阅读