[英]output is only last line of data. How to move my code around to fix this?
I've been moving my file.write expression in, out, and around the loop, but no matter what, I don't get the full list, only the last one.This problem has been addressed with Python: Only writes last line of output but that thread doesn't give a clear solution. 我一直在循环移动,移入和移出file.write表达式,但是无论如何,我没有得到完整列表,只有最后一个。Python解决了这个问题:只写最后一行输出,但该线程没有给出明确的解决方案。
I've tried with "w" and "a" but not successful with either.I also tried with "for line in f". 我曾尝试使用“ w”和“ a”,但均未成功。我也尝试过使用“ for f in line”。
The other issue is that what I want to output is a tuple, and when I print it, I get exactly what I want it to look like, ie 另一个问题是我要输出的是一个元组,当我打印它时,我得到的正是它想要的样子,即
14_sec.wav 14
16_sec.wav 16
but I've been converting it to a str in order to satisfy the write() requirement and so it doesn't appear that way in the output file. 但为了满足write()要求,我一直在将其转换为str,因此在输出文件中不会以这种方式出现。
My code is like this: 我的代码是这样的:
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))
I solved it by importing pandas and then exporting as a csv file, which worked great: 我通过导入大熊猫然后将其导出为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.