Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在提示符下使用Python打开文件_Python_Windows - Fatal编程技术网

在提示符下使用Python打开文件

在提示符下使用Python打开文件,python,windows,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)

从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)
通过对文本文件的filename参数调用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输出了以下内容:

File "<stdin>", line 1, in <module>
ImportError: No module named ex15_sample.txt
文件“”,第1行,在
ImportError:没有名为ex15_sample.txt的模块
如何通过Powershell命令行界面从Python中打开文件“ex15_sample.txt”

您需要为open()提供一个字符串

“ex15_sample.txt”是字符串文字,但ex15_sample.txt是尚未定义的变量的名称

所以,你需要打字

open("ex15_sample.txt")

这是一个非常基本的编程概念,当然不是Python特有的。将值传递给函数(如
open
)时,它可以是包含数据的变量,也可以是文字字符串。在这种情况下,您需要一个字符串,在大多数语言(包括Python)中,字符串必须用引号括起来:

x = open('ex15_sample.txt')
您误解了所读到的有关导入的内容:导入仅用于加载其他Python模块


还要注意的是,这些都与Powershell没有任何关系。

这样想,当您运行某个东西时,其中的所有单词都是命令(变量、函数等),python将尝试解释所有这些内容,当您尝试以下操作时:

open(ex15_sample.txt)
Python将有效地搜索一个命令
open
(它将查找,因为它是一个内置函数),然后它将搜索Python中不存在的另一个命令
ex15_sample
,因此它将抛出一个错误

您要做的是将包含文件名的文本传递给python,方法是用单引号或双引号将其括起来,
“ex15_sample.txt”
“ex15_sample.txt”
,这样python就可以将其解释为文本,而不是试图将其理解为命令,所以

open('ex15_sample.txt')

这才是你真正想要的

我不明白——我对这一点很陌生。什么是字符串文字?“为open()提供字符串”是什么意思?没问题!当您说
open(ex15_sample.txt)
Python查找名为ex15_sample的变量,并获取其属性txt。但是没有使用该名称定义变量!这就是为什么你会出错。字符串文字只是文本的集合。“ex15_sample.txt”是字符串文字。字符串是由双引号或单引号包围的一系列字符组成。例如,
“hello”
是一个字符串,而
hello
是一个变量。注意引号。
open()
函数要求括号之间有一个字符串。此时PowerShell的UI线程挂起在后台。Python继承PowerShell的控制台窗口并执行自己的控制台输入/输出(I/O)。它读取和写入控制台缓冲区句柄,控制台缓冲区句柄与另一个实际管理窗口的进程conhost.exe通信。感谢您的解释。
open('ex15_sample.txt')