gpt4 book ai didi

Python 3 - 从文件中读取文本

转载 作者:太空狗 更新时间:2023-10-30 01:44:58 24 4
gpt4 key购买 nike

这是 Learn Python the Hard Way 中的练习 15,但我使用的是 Python 3

from sys import argv
script, filename = argv

txt = open(filename)
print ("Here's your file %r:") % filename
print txt.read()

print ("I'll also ask you to type it again:")
file_again = input()
txt_again = open(file_again)
print txt_again.read()

文件保存为 ex15.py,当我从终端运行它时,它第一次正确读取 ex15.txt,但是当我第二次请求它时,出现错误

user@user:~/Desktop/python$ python ex15.py ex15.txt<br>
Here's your file 'ex15.txt':<br>
This is stuff I typed into a file.<br>
It is really cool stuff.<br>
Lots and lots of fun to have in here.<br>

I'll also ask you to type it again:<br>
ex15.txt <b>#now I type this in again, and I get a following error</b><br>
Traceback (most recent call last):<br>
File "ex15.py", line 11, in <<module>module><br>
file_again = input()<br>
File "<<string\>string>", line 1, in <<module>module><br>
NameError: name 'ex15' is not defined

怎么了?

最佳答案

您肯定没有使用 Python 3。有几件事使这一点显而易见:

  • 这些 print 语句没有括号(Python 3 要求但 2 不需要):

    print ("Here's your file %r:") % filename
    print txt.read()

    print txt_again.read()
  • 这正在调用 eval on input()这是changed in Python 3 :

    file_again = input()

很可能 Python 2 是您系统上的默认设置,但您可以通过将其添加为脚本的第一行来让您的脚本始终使用 Python 3(如果您直接运行它,例如 ./myscript .py):

#!/usr/bin/env python3

或者使用 Python 3 显式运行它:

python3 myscript.py

还有一点要注意:您应该在完成文件后真正关闭它。您可以明确地执行此操作:

txt = open(filename)
# do stuff needing text
txt.close()

或者使用 with statement并在 block 结束时处理它:

with open(filename) as txt:
# do stuff needing txt
# txt is closed here

关于Python 3 - 从文件中读取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com