简体   繁体   中英

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.

I've tried with "w" and "a" but not successful with either.I also tried with "for line in f".

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM