Python 区域:IOError:[Errno 22] 无效模式('w')或文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15141761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:27:52  来源:igfitidea点击:

Region: IOError: [Errno 22] invalid mode ('w') or filename

pythonioerror

提问by FaerieDrgn

I'm not sure why, but for some reason, whenever I have "region" in the file name of the output file, it gives me this error:

我不知道为什么,但出于某种原因,每当我在输出文件的文件名中有“区域”时,它都会给我这个错误:

IOError: [Errno 22] invalid mode ('w') or filename: 'path\regionlog.txt'

IOError: [Errno 22] 无效模式 ('w') 或文件名: 'path\regionlog.txt'

It does this for "region.txt", "logregion.txt", etc.

它为"region.txt""logregion.txt"等执行此操作。

class writeTo:
    def __init__(self, stdout, name):
       self.stdout = stdout
       self.log = file(name, 'w') #here is where it says the error occurs

output = os.path.abspath('path\regionlog.txt')
writer = writeTo(sys.stdout, output) #and here too

Why is this? I really would like to name my file "regionlog.txt" but it keeps coming up with that error. Is there a way around it?

为什么是这样?我真的很想将我的文件命名为“regionlog.txt”,但它不断出现该错误。有办法解决吗?

采纳答案by Pavel Anossov

Use forward slashes:

使用正斜杠:

'path/regionlog.txt'

Or raw strings:

或原始字符串:

r'path\regionlog.txt'

Or at least escape your backslashes:

或者至少逃避你的反斜杠:

'path\regionlog.txt'


\ris a carriage return.

\r是回车。



Another option: use os.path.joinand you won't have to worry about slashes at all:

另一种选择:使用os.path.join,您根本不必担心斜线:

output = os.path.abspath(os.path.join('path', 'regionlog.txt'))

回答by HymanChen

In C standard language, \t, \n, \rare escape characters. \tis a transverse to the next TAB position. \nis a newline and \ris a carriage return. You should use \\ror /r, and you will solve the problem!

在 C 标准语言中\t,, \n,\r是转义字符。\t是下一个 TAB 位置的横向。\n是换行符,\r是回车符。您应该使用\\r/r,您将解决问题!

回答by Henk van der Laak

Additionaly, Python also gives this message when trying to open a file > 50 MB from a SharePoint shared drive.

此外,当尝试从 SharePoint 共享驱动器打开大于 50 MB 的文件时,Python 也会显示此消息。

https://support.microsoft.com/en-us/help/2668751/you-cannot-download-more-than-50-mb-or-upload-large-files-when-the-upl

https://support.microsoft.com/en-us/help/2668751/you-cannot-download-more-than-50-mb-or-upload-large-files-when-the-upl

回答by Roee Anuar

Another simple solution is changing the "\r" instances in the filename path to "\R"

另一个简单的解决方案是将文件名路径中的“\r”实例更改为“\R”