【问题标题】:How to read the header of WAV file from FTP directly without downloading whole file in Python?如何直接从 FTP 读取 WAV 文件的标题而不用 Python 下载整个文件?
【发布时间】:2019-04-15 05:28:32
【问题描述】:

我想直接从 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)

【问题讨论】:

  • 所以你只有有一个 FTP 服务器,而不是 HTTP?
  • @MartinPrikryl 我能够在本地获取详细信息,但是当我尝试使用上面的解决方案时,我无法仅读取 wav 文件。如果我设法从 FTP 读取 WAV 文件,那么我现在如何获取 WAV 文件的详细信息
  • @MartinPrikryl 我已经完成了编辑。现在可以看到了
  • @MartinPrikryl 是的
  • @MartinPrikryl 好吧,对不起。你能帮我吗

标签: python python-2.7 ftp wav ftplib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2022-01-09
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多