首页 > 解决方案 > 从 sys 导入 argv 脚本,文件名 = argv,“testfile” txt = open(“testfile”,“r”

问题描述

我正在通过 zedd shaw 艰难地学习 python 并且每当我尝试读取文件时,它总是给我错误,即不存在这样的文件或目录,即使在文件存在之后也是如此

from sys import argv
script, filename = argv, "testfile"
txt = open("testfile","r")          

from sys import argv
script, filename = argv, "testfile"
txt = open("testfile","r")   

IOError Traceback (last last call last) in () 1 from sys import argv 2 script, filename = argv, "testfile" ----> 3 txt = open("testfile","r")

IOError:[Errno 2] 没有这样的文件或目录:'testfile'

标签: pythonpython-2.7

解决方案


如果您使用的是 windows,您应该配置您的文件夹以在文件浏览器中显示已知的扩展名,以便您拥有当前命名。

这是一个解释如何做的链接:https ://www.thewindowsclub.com/show-file-extensions-in-windows

如果您的文件命名良好,您可以安全地使用绝对路径:

import os
current_dir = os.path.dirname(__file__) # Absolute directory of the current python file
filename = "testfile.txt"
abs_file_path = os.path.join(current_dir, filename)

推荐阅读