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...

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.