So, I have been trying to make a program that will let me save the data in variables and put it in a txt file.?

Thing is that there are too many sites that say nothing that works so I came here. I am using 3.7.3 of python and I have no idea what I ned to do beyond:

filename = open("filename.txt", "w")

filename.write(variablename)

I have the file, it is where it needs to be and the variables are all strings but whenever I start the program it doesnt write anything. I have searched the web for 5 hours and found nothing so please help.

3 Answers

Relevance
  • keerok
    Lv 7
    1 month ago

    You can save the file but it's empty? Something wrong in the code somewhere.

    Can't save the file? Aside from the code, also check configuration, permission, location, and the firewall.

    If you can open the text file, read from it and display the contents onscreen, it is definitely possible to save it back to another text file.

    • Log in to reply to the answers
  • 1 month ago

    Would need to see more of the code to know if anything is actually being sent to the file.  If the variable is not receiving a value, the file would be empty.  If you are not closing the file when done, it could be empty.

    One thing to try is to have it write the data each time to the screen so you can see whether the issue is the data or the filewrite.

    • Log in to reply to the answers
  • 1 month ago

    You should learn how to produce files with the .write() file method, for sure, but it  is far easier to use print() to produce text files.

    If you know how to produce the output you want on the console, then the same print statements can be used for file output using the file=keyword argument to print():

    with open("hello.txt", "w") as print_file:

        print("Hello, Filesystem!", file=print_file)

        for n in range(16):

            print(n, "=", hex(n), file=print_file)

        print("Done.", file=print_file)

    Run that, then use a text editor (the one built into Idle or most any other IDE should work) to view the "hello.txt" file.

    The "with" statement is the recommended way to make sure that files are closed when you're done using them.  Output files, in particular, need to be properly closed to ensure that all data is correctly written. I don't know that this is an issue with Python 3.x, but it's a problem for enough languages on enough OSes to make it a Real Good Idea to close every file you open...especially output files.

    • Log in to reply to the answers
Still have questions? Get answers by asking now.