python - 在提示符中使用 Python 打开文件

标签 python windows

从 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/

相关文章:

python - 将 python 守护进程添加到 systemd

python - flask -socket.error : [Errno 10053] An established connection was aborted by the software in your host machine

python - 在 python 中转发属性查找

c - 驱动程序到用户模式通信

windows - 从 Windows 服务调用 MSIGetProductInfo 返回垃圾值

c++ - InterlockedDecrement 使用 XADD 但 InterlockedIncrement 使用 INC?

windows - 如何使用 mingw 启用 tbb 安装 opencv

windows - 有没有办法避免程序文件中自动运行应用程序的 UAC?

python - 使用 PyEnchant 语言词典创建词典

python - 检查包是否从源代码树中导入