输出只是最后一行数据。如何移动我的代码来解决这个问题?

2024-09-27 22:40:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在搬家文件.write表达式输入、输出和循环,但不管怎样,我都不会得到完整的列表,只有最后一个一个。这个问题已经用Python: Only writes last line of output解决了,但该线程并没有给出明确的解决方案。你知道吗

我试过用“w”和“a”,但都不成功。我也试过用“for line in f”。你知道吗

另一个问题是,我想要输出的是一个元组,当我打印它时,我得到的正是我想要的样子,即

    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))

Tags: 文件pathinforoswithlineres
1条回答
网友
1楼 · 发布于 2024-09-27 22:40:08

我通过导入熊猫然后导出为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))

相关问题 更多 >

    热门问题