[英]output is only last line of data. How to move my code around to fix this?
我一直在循环移动,移入和移出file.write表达式,但是无论如何,我没有得到完整列表,只有最后一个。Python解决了这个问题:只写最后一行输出,但该线程没有给出明确的解决方案。
我曾尝试使用“ w”和“ a”,但均未成功。我也尝试过使用“ for f in line”。
另一个问题是我要输出的是一个元组,当我打印它时,我得到的正是它想要的样子,即
14_sec.wav 14
16_sec.wav 16
但为了满足write()要求,我一直在将其转换为str,因此在输出文件中不会以这种方式出现。
我的代码是这样的:
path="/Volumes/LaCie/VoicemailDownload/test"
res_file = "fileLengths.csv"
for filename in os.listdir(path):
if filename.endswith(".wav"):
with open (filename, 'r') as f:
f.seek(28)
a = f.read(4)
byteRate=0
for i in range(4):
byteRate=byteRate + ord(a[i])*pow(256,i)
fileSize=os.path.getsize(filename)
ms=((fileSize-44)*1000)/byteRate
sec = ms/1000
res = filename, sec
print filename, sec
with open (res_file, "w") as results:
#for line in f:
results.write(str(res))
我通过导入大熊猫然后将其导出为csv文件来解决它,效果很好:
data = pandas.DataFrame([])
for filename in os.listdir(path):
if filename.endswith(".wav"):
f = open(filename, 'r')
f.seek(28)
a = f.read(4)
byteRate=0
for i in range(1,4):
byteRate=byteRate + ord(a[i])*pow(256,i)
fileSize=os.path.getsize(filename)
ms=((fileSize-44)*1000)/byteRate
sec = ms/1000
counter += 1
data = data.append(pandas.DataFrame({'Filename':filename, 'Sec': sec},index = [counter]), ignore_index=True)
newdata = data.to_csv(index=False)
with open(res_file, 'w') as results:
results.write(str(newdata))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.