如何打开文件并将其写入现有目录

2024-10-02 02:37:39 发布

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

我们是python新手,正在尝试写入现有目录中的新文件cyt_dir

outfile = open('cyt_dir/' +s+ ".html", "w")

但我们正在

IOerror [ERRno2] No such file or directory: 'cyt_dir/

为什么它不能识别目录?你知道吗


Tags: or文件no目录htmldiropendirectory
2条回答

你写的代码没问题。你知道吗

>>> s = "face"
>>> f = open('cyt_dir/' +s+ ".html", "w")
>>> f.write("testy testerson")
>>> f.close()

这将成功写入正确的目录。你得到的错误是一个IOerror,因此表明这里有其他的东西在起作用。你知道吗

查看python.org上的IOerror文档,我们可以看到出现这种情况的一些原因。No such file or directory给我提出了一些不同的建议。你知道吗

  1. 您正在一个不存在此文件夹结构的目录中运行python文件。你知道吗
  2. 您正在以可能没有该目录权限的用户身份运行python文件。(我怀疑另一种Errno会证明这一点)
  3. 你的硬盘已经满了,或者像这样愚蠢的东西。你知道吗

总之,这只是猜测。如果捕捉到错误,则可以从中获取更多信息:

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)

相关问题 更多 >

    热门问题