0

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()
1
  • 1
    your main function has no return value Commented May 12, 2016 at 23:44

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much - obviously I'm still learning. I really appreciate your explanation. This seems to have solved the problem.
1

You are calling print ord(byte) from within main(). This prints to the console.

You are also calling f.write(main()) which appears to assume that main() is going to return a value, but it doesn't.

It looks like what you intend to do is replace the print ord(byte) with a statement that appends your desired output to a string, and then return that string from your main() function.

Comments

1

You need to return the string from the function main. You are currently printing it and returning nothing. This will assemble the string and return it

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


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

1 Comment

thank you for the feedback, I can use all the help I can get :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.