I just started learning Python about 2 days ago, and I threw this program together, just to get the hang of it. The program just creates a file named "PythonTest.txt" in the same directory as the .py file. The user can then enter lines that are written to the .txt file. When they stop, it reads the file back to them. The only part giving me trouble right now is that when I call the function I created to read the file, none of the lines from the file show up. I know the file has text because I've opened up the .txt file and seen the text in it. Can anyone help with it? Here's all the code in the .py file:

filename = "PythonTest.txt"

# Define the readFile function
def readFile():
    print filename + ":\n\n"
    infile = file(filename, "r")
    for line in infile.readlines():
        print line  # Should print line from file but doesn't...

# Define the changeFile function
def changeFile():
    cont = "y"
    outfile = file(filename, "w")
    while cont == "y":
        intxt = raw_input("Enter line:\n\t")
        outfile.write(intxt + "\n")
        cont = raw_input("Keep writing?\t(y/n)\n\t")
    
    readFile()  # Call the readFile function

# Change file lines
change = raw_input("Do you want to change/create data in " + filename + "?\t(y/n)\n\t")
if change == "y":
    changeFile()  # Call the changeFile function
else:
    print "Closing..."
    # Make the program close here...

Dani AI

Generated

A short diagnosis and a few practical fixes. The behavior described by — seeing nothing when readFile() runs even though the text later appears in the .txt file — is exactly what happens when the program opens the file with mode 'w' and then never closes or flushes the writer. Opening with 'w' truncates the file on disk immediately; subsequent writes sit in a buffer. A separate read that opens the same filename will see the on-disk file (still empty) unless the writer has been flushed/closed. 's suggestion to call outfile.close() is the correct, minimal fix. Also close the reader when finished or use a context manager so closing is automatic.

Best practices and alternatives:

  • Prefer the context manager (with open(...) as f:). It guarantees the file is closed even on errors.
  • If reading and writing with the same handle is required, open with a read/write mode like 'w+', then f.flush() and f.seek(0) before reading. Otherwise, close the writer and open the file again for reading.
  • Move to Python 3 if possible: use open() and input() and print() (functions). Also be aware that in older Python 2 code, print line will add a newline if line already ends with \n, which can look like extra blank lines.

Example (Python 3, safe pattern):

filename = "PythonTest.txt"

def change_file():
    with open(filename, 'w', encoding='utf-8') as out:
        while True:
            line = input("Enter line (empty to stop): ")
            if not line:
                break
            out.write(line + '\n')

def read_file():
    print(filename + ":\n")
    with open(filename, 'r', encoding='utf-8') as f:
        for line in f:
            print(line, end='')

Quick checklist if problems persist: confirm the program's current working directory (absolute path), ensure no other process is locking the file, verify the correct filename/mode, and use with or explicit close() so buffers are flushed to disk.

Recommended Answers

All 3 Replies

Hi

The only part giving me trouble right now is that when I call the function I created to read the file, none of the lines from the file show up.

this is because you have to close the file, before reopening the same for reading. Here is your code below, with line included to close the file.
Look at line #18.

filename = "PythonTest.txt"

# Define the readFile function
def readFile():
    print filename + ":\n\n"
    infile = file(filename, "r")
    for line in infile.readlines():
        print line  # Should print line from file but doesn't...

# Define the changeFile function
def changeFile():
    cont = "y"
    outfile = file(filename, "w")
    while cont == "y":
        intxt = raw_input("Enter line:\n\t")
        outfile.write(intxt + "\n")
        cont = raw_input("Keep writing?\t(y/n)\n\t")
    outfile.close()#Closing the file
    readFile()  # Call the readFile function

# Change file lines
change = raw_input("Do you want to change/create data in " + filename + "?\t(y/n)\n\t")
if change == "y":
    changeFile()  # Call the changeFile function
else:
    print "Closing..."
    # Make the program close here...

Well, all the best, good going.

kath.

Thank you so much. I completely forgot about closing it. Thanks again!

Hey,

Also *close* the file after you finished with reading the file, in readFile() function. Even I forgot it..


kath.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.