【发布时间】:2017-11-20 03:24:35
【问题描述】:
查看我的问题here后,我发现这是由一个更简单的问题引起的。
当我将"\n" 写入文件时,我希望从文件中读取"\n"。在 Windows 中并非总是如此。
In [1]: with open("out", "w") as file:
...: file.write("\n")
...:
In [2]: with open("out", "r") as file:
...: s = file.read()
...:
In [3]: s # I expect "\n" and I get it
Out[3]: '\n'
In [4]: with open("out", "rb") as file:
...: b = file.read()
...:
In [5]: b # I expect b"\n"... Uh-oh
Out[5]: b'\r\n'
In [6]: with open("out", "wb") as file:
...: file.write(b"\n")
...:
In [7]: with open("out", "r") as file:
...: s = file.read()
...:
In [8]: s # I expect "\n" and I get it
Out[8]: '\n'
In [9]: with open("out", "rb") as file:
...: b = file.read()
...:
In [10]: b # I expect b"\n" and I get it
Out[10]: b'\n'
以更有条理的方式:
| Method of Writing | Method of Reading | "\n" Turns Into |
|-------------------|-------------------|-----------------|
| "w" | "r" | "\n" |
| "w" | "rb" | b"\r\n" |
| "wb" | "r" | "\n" |
| "wb" | "rb" | b"\n" |
当我在我的 Linux 虚拟机上尝试这个时,它总是返回 \n。如何在 Windows 中执行此操作?
编辑:
这对于 pandas 库尤其成问题,它似乎将DataFrames 写入csv 与"w" 并读取csvs 与"rb"。有关此示例,请参阅顶部链接的问题。
【问题讨论】:
-
在文本模式下,Python 将所有行尾替换为系统默认值。使用二进制模式并自己编码字符串以使用自定义行尾。
-
或者,在打开文件时指定行尾。这可能是一种更清洁的方法。
标签: windows python-3.x read-write