从 Windows Powershell 中调用 Python 后,我无法打开当前工作目录中的文件。
PS C:\python27> python
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel
Type "help", "copyright", "credits" or "license" for more information.
之后,我输入:
x = open(ex15_sample.txt)
通过对文本文件的文件名参数调用 open 函数的想法,我想在 Python 中打开它。我的想法是,然后我可以在 Windows Powershell 中运行以下代码,并通过 Powershell 在 Python 中打开该文件:
print x.read()
但是我无法到达这一步,因为在我输入
之后x = open(ex15_sample.txt)
Powershell 输出以下内容:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ex15_sample' is not defined
为了通过 Powershell 在 Python 中打开文件“ex15_sample.txt”,我还输入了:
import ex15_sample.txt
在网上阅读后发现这可以工作,但 Powershell 输出以下内容:
File "<stdin>", line 1, in <module>
ImportError: No module named ex15_sample.txt
如何通过 Powershell 命令行界面从 Python 中打开文件“ex15_sample.txt”?
最佳答案
您需要向 open() 提供一个字符串。
“ex15_sample.txt”是字符串文字,但 ex15_sample.txt 是您尚 undefined variable 的名称。
因此,您需要输入
open("ex15_sample.txt")
关于python - 在提示符中使用 Python 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27882367/