Python readline() not working?

醉酒当歌 提交于 2019-12-12 21:03:55

问题


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?


回答1:


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.




回答2:


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.




回答3:


The Python interpreter runs in two different modes:

  1. The interactive mode, which shows the >>> command prompt and can be accessed by simply typing python or python.exe into the command prompt. This mode has an echo feature which conveniently displays for you the return value of any function or expression you type.

  2. The script mode. When you type into the command line python <yourscript.py>. In this mode, Python hides your script, as well as the return values for the statements you type.

If you want a Python script to display something in the console, use the print() function.

print(f.readlines())

See python.org for more about the Python interpreter.



来源:https://stackoverflow.com/questions/8956626/python-readline-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!