Why is my Python script not writing the last few l

2020-04-14 07:07发布

问题:

I've been trying to read lists of numbers from one file, split them up, and put them into another file. After messing with a few debug prints, I've come to the conclusion that the issue isn't with the looping or splitting of my strings, but rather with the very last line of the script where I actually write to the new file.

Rather than just write as I'd want it to, it gets most of the way through the file, and then just doesn't write the last few lines of the file. Is there some limit to the number of things I can write in a script? Or is something else going on here?

Here's the script: import string

#constants to name out in/out files
INFILE = 'newkicBright.txt'
OUTFILE = 'out.txt'

#open both files
inHandle = open(INFILE, 'r')
outHandle = open(OUTFILE, 'w')

#console verifies that everything's opened
print inHandle
print outHandle

#read our data into the file!
for line in inHandle:
    nums = string.split(line)
    for num in nums:
        num += " PLACEHOLDER\n"
        outHandle.write(num)

回答1:

You need to close your file handler so it actually writes and cleans everything up.

outHandle.close()

add that to the end.

close implies flush: does close() imply flush() in Python?