Maggie Maggie - 6 months ago 10
Python Question

Writing to txt file in Python

I'm having issues printing to a txt file. The file contains information stored in bytes. No matter what I try, I can only get the output to print in the shell. Here's what I have - any help is welcome.

def main():
with open("in.txt", "rb") as f:
byte = f.read(1)
while byte != "":
print ord(byte),
byte = f.read(1)


with open('out.txt','w') as f:
if __name__ == '__main__':
f.write(main())
close.f()

Answer

This is a fundamental misunderstanding of what various functions and methods do. You are writing the returned value of main() to the file, expecting main's print() calls to go to the file. It does not work like that.

def main():
    with open("in.txt", "rb") as f, open('out.txt','w') as output:
        byte = f.read(1)
        while byte != "":
            output.write(str(ord(byte))) 
            byte = f.read(1)

if __name__ == '__main__':
    main()

Use file.write() to write strings (or bytes, if you're using that kind of output, which you currently aren't) to a file. For your code to work, main() would have to return a complete string with the content you wanted to write.

Comments