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

Fae*_*rgn 21 python ioerror

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

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

它为"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
Run Code Online (Sandbox Code Playgroud)

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

Pav*_*sov 32

使用正斜杠:

'path/regionlog.txt'
Run Code Online (Sandbox Code Playgroud)

或原始字符串:

r'path\regionlog.txt'
Run Code Online (Sandbox Code Playgroud)

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

'path\\regionlog.txt'
Run Code Online (Sandbox Code Playgroud)

 

\r 是回车.

 

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

output = os.path.abspath(os.path.join('path', 'regionlog.txt'))
Run Code Online (Sandbox Code Playgroud)