python - 在python中读/写txt文件后文件大小发生变化

标签 python filesize read-write

执行以下代码以使用 Python 生成文本文件的副本后,newfile.txt 的文件大小与 oldfile.txt 不完全相同.

with open('oldfile.txt','r') as a, open('newfile.txt','w') as b:
    content = a.read()
    b.write(content)

虽然 oldfile.txt 有例如667 KB,newfile.txt 有 681 KB。

有人对此有解释吗?

最佳答案

有多种原因。

您将文件作为文本文件打开,因此文件的字节被解释(解码)为 python,然后进行编码。所以可能会有变化。

来自打开文档(https://docs.python.org/3/library/functions.html#open):

When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.

因此,如果原始文件是 ASCII(例如在 Windows 中生成),您将删除 \r。但是当写回文件时,你不能再拥有原始的 \r(如果你在 Linux 或 MacOs 中)或者你将始终拥有 \r\n,如果你在 Windows 上(看起来是这样,因为你的文件大小增加了)。

编码也可以改变文本。例如。可以删除(或添加)BOM 标记,并且可能(但 AFAIK 它不是隐式完成的)可以删除不需要的代码(您可以在 Unicode 中添加一些额外的代码,这会改变附近代码的行为。可以添加更多的其中之一,但只有最后一个有效。

关于python - 在python中读/写txt文件后文件大小发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49273932/

相关文章:

python + gstreamer 插件

python - python中的排序函数

r - 如何减少 r 中预处理配方对象的大小?

C++ stat.h 类型不完整且无法定义

c++ - 读取硬盘字节

python - 从Python中的字符串中捕获选定的文本

python - 我如何结合 SQLAlchemy 和 EAV DB 模式的优势?

c - 编写简单的 du clone。获取子目录中文件大小的随机值。

java - 如何在读/写中拆分 tex 文件中的一行?

Bash:在设备上写入然后从中读取