以'rt'和'wt'模式打开文件

ale*_*cxe 94 python file-io file

在这里几次我已经看到人们使用rtwt模式来读写文件.

例如:

with open('input.txt', 'rt') as input_file:
     with open('output.txt', 'wt') as output_file: 
         ...
Run Code Online (Sandbox Code Playgroud)

我不明白的方式记载,但因为open()不抛出一个错误-看起来几乎是合法的使用.

是什么状况,使用wtvs wrtvs 之间有什么区别r吗?

dev*_*ull 165

t指文本模式.rrt或之间没有区别w,wt因为文本模式是默认模式.

记录在这里:

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

默认模式是'r'(打开以读取文本,同义词'rt').

  • 注意`w`并不总是等于`wt`.其中一个例子是[`gzip.open`](https://docs.python.org/3/library/gzip.html#gzip.open),其中二进制模式是默认模式,而不是文本模式.相关问题:http://stackoverflow.com/questions/42013083/python-3-gzip-open-and-modes (5认同)
  • 知道了,它在python3文档中有记录.所以,`wt` vs`w`和`rt` vs`r`之间基本上没有区别 - 只是`显式比隐式更好? (4认同)

ʇsә*_*ɹoɈ 9

t显示文本模式,这意味着\n字符将写入文件时,读取时被翻译成主机OS行结束,然后再返回.该标志基本上只是噪音,因为文本模式是默认值.

比其他的U那些模式标志直接从C标准库的到来fopen()功能,即在第六段记录的事实python2文档open().

据我所知,t不是也从未成为C标准的一部分,所以尽管C库的许多实现仍然接受它,但不能保证它们都会,但不保证它将适用于每个构建的蟒蛇.这就解释了为什么python2文档没有列出它,以及为什么它一般都有效.该python3文档使它官员.