获取“IOError:[Errno 2]没有这样的文件或目录:“myoutfile.csv” ” Python 中的错误

发布于 2024-12-08 04:31:55 字数 268 浏览 1 评论 0原文

我正在使用这一行创建一个新文件(该文件不存在):

with open(outfilename, 'rwb') as outfile:

它收到此错误:

IOError: [Errno 2] No such file or directory: 'myoutfile.csv'

我正在尝试创建此文件,我想如果我使用“w”,如果不存在,就会创建它存在。如果是权限,如何新建文件夹并引用其路径?

I am using this line to create a new file (the file does not exist):

with open(outfilename, 'rwb') as outfile:

And it gets this error:

IOError: [Errno 2] No such file or directory: 'myoutfile.csv'

I am trying to create this file, and I thought if I used 'w' that would create it if it doesn't exist. If it is permissions, how do I create a new folder and refer to its path?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゃ懵逼小萝莉 2024-12-15 04:31:55

传递给 open() 函数的打开模式仅接受少数特定的字母组合。在你的例子中,'rwb'不是这些组合之一,Python可能假设你的意思是'rb'。尝试:

with open(outfilename, 'wb') as outfile:

这将打开文件进行写入。如果您需要写入从同一个句柄读取,请使用:

with open(outfilename, "w+b") as outfile:

The open mode passed to the open() function accepts only a specific few combinations of letters. In your case, 'rwb' is not one of those combinations, and Python is perhaps assuming that you meant 'rb'. Try:

with open(outfilename, 'wb') as outfile:

This opens the file for writing. If you need to both write to and read from the same handle, use:

with open(outfilename, "w+b") as outfile:
冷心人i 2024-12-15 04:31:55

我非常确定 rwb 不是 open 的有效模式。根据所需的行为,您可能必须选择 r+bw+b 之一。

如果您想读取现有文件,请使用rb

如果您想读取/写入现有文件,请使用r+b

使用 wb 是您想要写入现有或不存在的文件(将首先截断现有文件)。

使用 w+b 是您想要读/写现有或不存在的文件(将首先截断现有文件)。

如果您不想截断现有文件,请使用组合,例如(显然是伪代码):

open with "r+b"
on error:
    open with "w+b"

I'm pretty certain rwb isn't a valid mode for open. Depending on the behaviour desired, you may have to opt for one of r+b or w+b.

Use rb is you want to read an existing file.

Use r+b is you want to read/write an existing file.

Use wb is you want to write an existing or non-existing file (will truncate an existing file first).

Use w+b is you want to read/write an existing or non-existing file (will truncate an existing file first).

Use a combination if you don't want truncation of an existing file, something like (pseudo-code, obviously):

open with "r+b"
on error:
    open with "w+b"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文