【问题标题】:python file write is not creating a new filepython文件写入没有创建新文件
【发布时间】:2019-11-11 03:14:42
【问题描述】:

我有一个 django 应用程序,我从一个 javascript 客户端接收到二进制音频数据,我正在尝试将它发送到谷歌云语音到文本 API。问题是,python 没有将二进制音频数据写入文件。所以我得到了

with io.open(file_name, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: '.........\\gcp_cloud\\blog\\audio_file.wav'

我用......替换了路径的第一部分

这是客户端代码

        rec.ondataavailable = e => {
          audioChunks.push(e.data);
          if (rec.state == "inactive"){
            let blob = new Blob(audioChunks,{type:'audio/wav; codecs=MS_PCM'});
            recordedAudio.src = URL.createObjectURL(blob);
            recordedAudio.controls=true;
            recordedAudio.autoplay=true;
            sendData(blob)
          }
        }

这是我的 sendData 函数

function sendData(data) {
    let csrftoken = getCookie('csrftoken');
    let response=fetch("/voice_request", {
    method: "post",
    body: data,
    headers: { "X-CSRFToken": csrftoken },
    })

    console.log('got a response from the server')
    console.log(response)
}

这是处理来自客户端的二进制音频数据的 DJango 视图

def voice_request(request):
    #print(request.body)
    fw = open('audio_file.wav', 'wb')
    fw.write(request.body)
    file_name = os.path.join(current_folder, 'audio_file.wav')
    #file_name = os.path.join(current_folder, 'Recording.m4a')
    client = speech.SpeechClient()

    # The language of the supplied audio
    language_code = "en-US"

    # Sample rate in Hertz of the audio data sent
    sample_rate_hertz = 16000

    encoding = enums.RecognitionConfig.AudioEncoding.LINEAR16
    config = {
        "language_code": language_code,
        #"sample_rate_hertz": sample_rate_hertz,
        #"encoding": 'm4a',
    }
    with io.open(file_name, "rb") as f:
        content = f.read()

    audio = {"content": content}

    fw.close()

    response = client.recognize(config, audio)

    print('response')
    print(response)
    for result in response.results:
        # First alternative is the most probable result
        alternative = result.alternatives[0]
        print(u"Transcript: {}".format(alternative.transcript))

    return HttpResponse(response)

【问题讨论】:

  • 你为什么不为’audio_file.wav’ 使用上下文管理器?另外,您在代码中的哪个位置创建文件?我不确定我是否理解问题所在,据我所知,您正在尝试读取一个不存在的文件,这显然会导致错误。
  • 在voice_request 视图中保存文件audio_file.wav 后,是否会保存一个有效的wav 文件。同样,当使用 fw.write(request.body) 保存时,您正在写入当前文件夹。那么为什么不直接从当前文件夹读取它而不用 os.path.join(current_folder.... 指定完整路径....
  • @AlexanderCécile 我不知道上下文管理器是什么,但我会查一下。我正在写入一个文件fw.write(request.body),我认为如果它不存在,这将创建一个文件,并覆盖现有文件。由于它不起作用,我将如何实现这种效果?
  • @bhaskarc 我在工作目录中看不到文件。我想这并不是真正写入文件。我将其更改为直接指定文件,现在我没有收到文件未找到错误,但谷歌云 API 没有返回任何响应。而且我仍然无法在我的目录中看到该文件。
  • @Rockstar5645 据我所知,如果文件不存在,open(..., ‘wb’) 应该 创建文件。上下文管理器是使用 with 语句创建的,您已经在代码的其他地方使用了它!更改它以使用上下文管理器,看看是否可以解决问题?

标签: python django python-2.7


【解决方案1】:

您应该使用with io.open(file_name, "wb") as f: 或with io.open(file_name, "ab") as f: 因为r 表示只读,w 表示“重写”

您可以参考:https://docs.python.org/3.7/library/functions.html?highlight=open#open

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2021-06-17
    • 2016-05-17
    • 2022-12-09
    • 1970-01-01
    • 2011-06-22
    相关资源
    最近更新 更多