[英]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.