Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

Python声明我的文件不在目录中,即使它保存在我的计算机上。怎么了?

Python声明我的文件不在目录中,即使它保存在我的计算机上。怎么了?,python,python-3.x,Python,Python 3.x,假设包含一系列整数的文件名为numbers.txt,并且存在于 计算机的磁盘。编写一个程序,计算存储在内存中的所有数字的平均值 档案 我的计算机上保存了一个文件名numbers\u good.txt。当我在错误中键入时,在目录中没有读取任何文件 def main(): try: filename=input("name of the file") myfile=open(filename, "r") except IOError:

假设包含一系列整数的文件名为numbers.txt,并且存在于 计算机的磁盘。编写一个程序,计算存储在内存中的所有数字的平均值 档案

我的计算机上保存了一个文件名
numbers\u good.tx
t。当我在错误中键入时,在目录中没有读取任何文件

def main():
    try:
        filename=input("name of the file")
        myfile=open(filename, "r")
    except IOError:
        print("File Error")

main()

这很可能是相对路径的问题。可能由于某种原因,您的程序的工作目录不是您所期望的

试试这个程序,看看Python实际上在哪里查找您的文件

import os.path

filename = input("name of the file: ")
print(os.path.abspath(filename))

您应该输入绝对路径或将文件移动到工作目录中(您可以从我发布的程序的输出中推断出来)。

您的程序对我来说运行良好。如果我将其命名为“input.py”,并从shell提示符运行
python input.py
,然后在程序提示时键入
input.py
,则不会出现错误。我想知道您的文件是否位于与您认为的不同的目录中?我想是的,如何更改路径目录?请注意,您应该始终使用Python打开文件。谢谢。不幸的是,我能使用你的代码。我必须坚持我写的格式,因为这个程序是一个作业。@DaveLee我想你没有领会kirelagin的意思:他向你展示了如何看到完整路径,这样你就可以看到它是否符合你的预期。在作业中,你可以写任何你想写的代码,只要它有效。例如,您可以创建一个字符串变量,它可以是您想要搜索的路径,也可以是可执行文件的主路径。然后将文件名粘贴到该路径&voila,它现在正在寻找正确的位置。+1:@kirelagin的代码将有助于诊断问题(即Python脚本认为文件应该在哪里),即使它本身不能用于分配。我们大多数人可能犯的一个简单错误是,我们可能会隐藏文件的扩展名(通常发生在windows中)。可能是您创建了一个txt文件,然后在隐藏扩展名时将其命名为numbers.txt。实际上,文件名将为numbers.txt.txt