Python2.7:为什么python不读取我的任何带有open(文件名)的路径?

2024-05-08 22:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,在练习15的“努力学习python”中,您将学习如何让程序打开文件。这是我的代码,我在命令提示符下键入了python ex15.py ex15.txt。到目前为止,我还没有遇到任何其他问题:

from sys import argv

script, filename = argv

txt = open(ex15.txt)

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

print "type the filename again: "
again = raw_input("> ")

again2 = open(again)
print again2.read()

下面是错误信息:

Traceback (most recent call last):
  File "ex15.py", line 5, in <module>
    txt = open("ex15.txt")

IOError: [Errno 2] No such file or directory: 'ex15.txt'

我立刻怀疑问题是文件没有放在正确的位置(ex15.txt),并将其放在Windows中的Python27文件夹中。然后在互联网上对这个问题做了一些研究之后,我试着把它放在cmd的工作目录中,也放在Python27scripts文件夹中,还试着包含原始文件位置(文档)的完整路径名,我总是得到相同的错误消息。你知道吗

我(或我的电脑)在这里缺什么?脚本的路径是C:\Python27,提示符的目录是C:\Users\Customer,我已经说明了文本文件的所有位置,它仍然在每个文件夹中。python程序确实包含在PATH中。你知道吗


Tags: 文件py程序txt文件夹readopenfilename
2条回答

文件必须位于运行脚本的同一文件夹中

如果您在C:/myscript.py运行,那么您的文件也需要在C:/运行。你知道吗

例如:

>> cd C:
>> dir
ex15.txt  myscript.py
>> python myscript.py ex15.txt
Here's your file: 'ex15.txt'
Something that is in your text file

type the filename again: 
> ex15.txt
Something that is in your text file

而且,您的代码似乎是错误的。您需要使用“ex15.txt”,而不是没有引号的ex15.txt。否则它将被解释为变量,而不是字符串。你知道吗

请参见下面的代码:

from sys import argv

script, filename = argv

txt = open("ex15.txt")

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

print "type the filename again: "
again = raw_input("> ")

again2 = open(again)
print again2.read()

你一直在读泽德的《艰难地学习Python》肖。唐不能说是 txt=打开(ex15.txt) 而是使用: txt=打开(文件名)。 您使用的是参数变量,它们就像原始输入,需要改变

相关问题 更多 >