IOError: [Errno 22] 无效模式 ('r') 或文件名: 'c:\\Python27\test.txt'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15598160/
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 20:30:55  来源:igfitidea点击:

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

pythonfile-io

提问by Brian Teece

What is wrong with the following:

以下有什么问题:

test_file=open('c:\Python27\test.txt','r')

采纳答案by Martijn Pieters

\tis a tab character. Use a raw string instead:

\t是制表符。改用原始字符串:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

或双斜线:

test_file=open('c:\Python27\test.txt','r')

or use forward slashes instead:

或使用正斜杠代替:

test_file=open('c:/Python27/test.txt','r')

回答by svk

\tin a string marks an escape sequence for a tab character. For a literal \, use \\.

\t在字符串中标记制表符的转义序列。对于文字\,请使用\\.

回答by Scintillo

\is an escape character in Python. \tgets interpreted as a tab. If you need \character in a string, you have to use \\.

\是 Python 中的转义字符。\t被解释为一个选项卡。如果需要\字符串中的字符,则必须使用\\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

你的代码应该是:
test_file=open('c:\\Python27\\test.txt','r')

回答by Yarkee

always use 'r' to get a raw string when you want to avoid escape.

当您想避免转义时,请始终使用 'r' 来获取原始字符串。

test_file=open(r'c:\Python27\test.txt','r')