以“rt”和“wt”模式打开文件

因此,我已经看到有人使用rtwt模式来读取和写入文件。

例如:

 with open('input.txt', 'rt') as input_file: with open('output.txt', 'wt') as output_file: ... 

我没有看到logging的模式,但由于open()不会抛出一个错误 – 看起来这是非常合法的使用。

这是什么和使用wt vs wrt vs r有什么区别?

t是指文本模式。 rrtwwt没有区别,因为文本模式是默认的。

logging在这里 :

 Character Meaning 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' open for exclusive creation, failing if the file already exists 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newlines mode (deprecated) 

t表示文本模式,这意味着在写入文件时\n字符将被转换为主机操作系统行结束符,并在读取时再次返回。 标志基本上只是噪音,因为文本模式是默认的。

U ,这些模式标志直接来自标准C库的fopen()函数,在open()的python2文档的第六段中logging了这一事实。

据我所知, t不是,也不是C标准的一部分,所以尽pipeC库的很多实现都接受它,但是不能保证它们全都可以,因此也不能保证它能在每一个构build中工作的python。 这就解释了为什么python2文档没有列出,为什么它一般工作。 python3文档使其正式。

'r'是阅读,'w'是写作,'a'是附加。

't'表示文本模式为二进制模式。

因此,我已经看到有人使用rt和wt模式来读取和写入文件。

编辑:你确定你看到rt而不是rb?

这些函数通常包含这里描述的fopen函数:

http://www.cplusplus.com/reference/cstdio/fopen/

正如你所看到的,它提到使用b以二进制模式打开文件。

您提供的文档链接也参考了这个b模式:

即使在不把二进制和文本文件作为文档处理的系统上,附加'b'也是有用的。

t表示text mode

https://docs.python.org/release/3.1.5/library/functions.html#open

在linux上,文本模式和二进制模式没有什么区别,但是在windows中,它们在文本模式下将\n转换为\r\n

http://www.cygwin.com/cygwin-ug-net/using-textbinary.html