假设包含一系列整数的文件名为numbers.txt并且存在于 电脑的磁盘。编写一个程序,计算存储的所有数字的平均值 文件。
我的计算机上保存了文件名numbers_good.tx
。当我在错误中键入它时,在目录中读取没有文件。
def main():
try:
filename=input("name of the file")
myfile=open(filename, "r")
except IOError:
print("File Error")
main()
答案 0 :(得分:4)
这很可能是相对路径的问题。可能由于某种原因,您的程序的工作目录不是您期望的那个。
试试这个程序,看看Python实际上在哪里寻找你的文件。
import os.path
filename = input("name of the file: ")
print(os.path.abspath(filename))
您应该输入absoulte路径或将文件移动到工作目录中(您可以从我发布的程序的输出中推断出它。)