不能多次写入文件。收到Errno 13权限被拒绝

时间:2019-07-04 23:10:23

标签: python

我不确定为什么会出现权限错误,但是我正在使用Google的文本语音API将数据写入.mp3文件。这是我从他们那里获取的代码,并将其放入一个函数中。

"""Synthesizes speech from the input string of text or ssml.

Note: ssml must be well-formed according to:
    https://www.w3.org/TR/speech-synthesis/
"""
from google.cloud import texttospeech

def gen_speech(num):
    # Instantiates a client
    client = texttospeech.TextToSpeechClient()

    # Set the text input to be synthesized
    synthesis_input = texttospeech.types.SynthesisInput(text=f'{num}')

    # Build the voice request, select the language code ("en-US") and the ssml
    # voice gender ("neutral")
    voice = texttospeech.types.VoiceSelectionParams(
        language_code='ja-JP',
        ssml_gender=texttospeech.enums.SsmlVoiceGender.NEUTRAL)

    # Select the type of audio file you want returned
    audio_config = texttospeech.types.AudioConfig(
        audio_encoding=texttospeech.enums.AudioEncoding.MP3)

    # Perform the text-to-speech request on the text input with the selected
    # voice parameters and audio file type
    response = client.synthesize_speech(synthesis_input, voice, audio_config)

    # The response's audio_content is binary.
    with open('output.mp3', 'wb') as out:
        # Write the response to the output file.
        out.write(response.audio_content)
        print('Audio content written to file "output.mp3"')

这是我的app.py代码。

from speech import gen_speech
import random
from playsound import playsound

def get_input():
    user_input = input("Enter the number: ")
    return user_input


def main():
    while True:
        num = random.randint(0, 5)
        gen_speech(num)  # generate speech
        playsound('output.mp3')
        user_input = int(get_input())
        if user_input != num:
            print('Incorrect. Listen closely')
            while user_input != num:
                playsound('output.mp3')
                user_input = int(get_input())
        print('Correct!')
        break
    gen_speech(10)
    playsound('./output.mp3')


if __name__ == '__main__':
    main()

该程序的目的只是输入您听到的内容。由于某种原因,在gen_speech()中写入output.mp3的工作在第一次调用时有效,但是在第二次调用时有效(无论是在while循环中的if语句中还是在while循环的另一个迭代中)此权限错误。不幸的是,您不能使用os.chmod()将写入和执行位都更改为7。有谁知道我如何才能更改此文件的权限才能工作和/或为什么我会收到此错误?同样值得注意的是,Python也会创建文件。我没有事先创建。

0 个答案:

没有答案