【发布时间】:2018-05-01 00:31:35
【问题描述】:
我想知道是否有办法找到临时文件的路径而不返回 int(在我的情况下为 15)。我想返回一个字符串(或一个对象,然后我可以在其中变成一个,请详细说明如何)路径是临时文件的路径(及其名称)。示例:/Users/FooBar/Python3.6/Modules/TempFile/Opus/THE_TEMP_FILE 或类似的东西。我已经为它编写了一个小的 .wav 文件,并希望使用 os .stat() 获取路径以获取它的播放时间/持续时间。我想使用一个临时文件,因为我很懒,而且我不想为我试图在这个程序上运行的四种不同的操作系统做很多“特殊”代码。这是我的代码:
import pygame, time, os, tempfile
import urllib.request as ur
pygame.init() # Initialize the pygame
DISPLAYSURF = pygame.display.set_mode((1, 1)) # Sets display. Needed to play sound
sound = input('What sound should play: ') # Asks which sound
url = 'http://207.224.195.43:8000/' + sound # Gets server url
response = ur.urlopen(url) # Open url
data = response.read() # Create byte like object containing .wav code
f = tempfile.TemporaryFile() # Create TempFile
f.write(data) # Write .wav data gotten from server
f.seek(0) # Prepare to read it
soundObj = pygame.mixer.Sound(f.read()) # Load sound to be played
f.seek(0) # Prepare to read it
statbuf = os.stat(f.name) # Gets stats from TempFile. Returns int, I want to fix that
mbytes = statbuf.st_size / 1024 # Gets 'not real' sound duration
soundObj.play() # Plays sounds
time.sleep(mbytes / 200) # Gets 'real' sound duration and waits
soundObj.stop() # Stops sounds once done
如果您有任何建议,请告诉我(评论)。我查看了几个站点,其中一个是关于堆栈溢出的,您可能会误认为是这个问题的重复。这是关于 Django 的,据我所知,它与 python 完全不同。感谢您可能回答这个问题。请记住,我不是在寻找关于这是一个问题的确认,我已经知道了。请尽快给我一个可能的答案。 谢谢!
-用户9311010
【问题讨论】:
-
(1) Django 与 Python 并不完全不同;它是一个用 Python 编写并用于 Python 代码的框架。 (2) 只是说你看过其他可能看起来像重复的答案是没有帮助的。告诉我们哪些答案。否则,有人很可能会错误地关闭您的问题作为其中一个问题的副本,或者给出对您不起作用的相同答案,因为没有人有任何方式猜测您已经尝试过该答案。
标签: python python-3.x temporary-files