问题
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:
The interactive mode, which shows the
>>>
command prompt and can be accessed by simply typingpython
orpython.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.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