[英]How to open and write a file into an existing directory
We are new to python and trying to write to a new file in an existing directory cyt_dir
我们是python的新手,正在尝试写入现有目录
cyt_dir
的新文件
outfile = open('cyt_dir/' +s+ ".html", "w")
but we are getting 但是我们越来越
IOerror [ERRno2] No such file or directory: 'cyt_dir/
IOerror [ERRno2]没有这样的文件或目录:'cyt_dir /
why doesn't it recognise the directory? 为什么无法识别目录?
The code you have written works no problem. 您编写的代码没有问题。
>>> s = "face"
>>> f = open('cyt_dir/' +s+ ".html", "w")
>>> f.write("testy testerson")
>>> f.close()
This succesfully writes to the correct directory. 这将成功写入正确的目录。 The error you got is an IOerror and so suggests something else is at play here.
您遇到的错误是IOerror,因此建议此处还有其他问题。
Looking at the IOerror documentation on python.org we can see some reasons as to why this might pop up. 综观上的ioerror文档python.org我们可以看到一些原因,为什么这可能会弹出。
No such file or directory
suggests a few different things to me. No such file or directory
向我建议一些不同的东西。
Errno
would demonstrate that) Errno
会证明这一点) All in all this is just speculation. 总而言之,这仅仅是猜测。 You might be able to get more info from the error if you catch it:
如果捕获到该错误,则可能能够从该错误中获取更多信息:
try:
f = open('cyt_dir/' +s+ ".html", "w")
except IOError, e:
print "Not allowed", e
Most likely this is current path issue, you need to know where you are executing your script from. 这很可能是当前路径问题,您需要知道从哪里执行脚本。 Or, as an alternative, provide an absolute path instead of relative
cyt_dir
. 或者,可以选择提供绝对路径,而不是相对
cyt_dir
。
I would pick third variant and would write a mechanism that extracts the path from script location, so that you are always safe, not matter what: 我将选择第三个变体,并编写一种从脚本位置提取路径的机制,因此无论什么情况,您始终是安全的:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.