2024-10-02 02:37:39 发布
网友
我们是python新手,正在尝试写入现有目录中的新文件cyt_dir
cyt_dir
outfile = open('cyt_dir/' +s+ ".html", "w")
但我们正在
IOerror [ERRno2] No such file or directory: 'cyt_dir/
为什么它不能识别目录?你知道吗
你写的代码没问题。你知道吗
>>> s = "face" >>> f = open('cyt_dir/' +s+ ".html", "w") >>> f.write("testy testerson") >>> f.close()
这将成功写入正确的目录。你得到的错误是一个IOerror,因此表明这里有其他的东西在起作用。你知道吗
查看python.org上的IOerror文档,我们可以看到出现这种情况的一些原因。No such file or directory给我提出了一些不同的建议。你知道吗
No such file or directory
Errno
总之,这只是猜测。如果捕捉到错误,则可以从中获取更多信息:
try: f = open('cyt_dir/' +s+ ".html", "w") except IOError, e: print "Not allowed", e
很可能这是当前的路径问题,您需要知道从何处执行脚本。或者,也可以提供一个绝对路径,而不是相对路径。你知道吗
我会选择第三种变体,并编写一种机制,从脚本位置提取路径,这样您就永远安全了,不管发生什么:
path = os.path.dirname(os.path.abspath(__file__)) try: outfile = open("%s/cyt_dir/%s.html".format(path, s), "w") except IOError as e: print "I/O error({0}): {1}".format(e.errno, e.strerror)
你写的代码没问题。你知道吗
这将成功写入正确的目录。你得到的错误是一个IOerror,因此表明这里有其他的东西在起作用。你知道吗
查看python.org上的IOerror文档,我们可以看到出现这种情况的一些原因。
No such file or directory
给我提出了一些不同的建议。你知道吗Errno
会证明这一点)总之,这只是猜测。如果捕捉到错误,则可以从中获取更多信息:
很可能这是当前的路径问题,您需要知道从何处执行脚本。或者,也可以提供一个绝对路径,而不是相对路径。你知道吗
我会选择第三种变体,并编写一种机制,从脚本位置提取路径,这样您就永远安全了,不管发生什么:
相关问题 更多 >
编程相关推荐