Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python readline() not working?

I am doing a small program to help me with learning Python (which I am very new to). I'm using Python 3.2.

In the Python shell, when I enter

f = open('filename.txt', 'r')
f.readlines()

it prints everything in the filename.txt. However, when I type it in a new window and save it with the .py extension, it does not show any output when I run it. It also does not give me any errors.

The code looks somewhat like this:

f = open('filename.txt', 'r')
f.readlines()

while True:
    f = open('filename.txt', 'a')
    inp = input('Enter text: ')
    rest of code...

How do I print everything in the file before going through any of the while statement?

like image 965
Mike Avatar asked Dec 31 '25 16:12

Mike


2 Answers

however when I type it in a new window and save it with the .py extension

Add a print call. The interactive toplevel prints the value of the last expression entered for convenience, but in a script this would soon get very annoying.

like image 134
Fred Foo Avatar answered Jan 02 '26 05:01

Fred Foo


Try this in your code:

print(f.readlines())

The shell evaluates and prints the result of each expression you type, but if you intend to run your program from a file, then you must explicitly print the values that you want to see in the console.

like image 25
Óscar López Avatar answered Jan 02 '26 06:01

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!