【问题标题】:file size difference -python文件大小差异-python
【发布时间】:2018-01-26 03:37:40
【问题描述】:

当我使用 st_size 读取文件大小时,我得到 11264 字节

k = os.stat(r"C:\Users\sakth\Desktop\ASRS.txt")
print(k.st_size)

但是当我以块的形式读取文件并总结它们的字节时,我只得到 11060 字节。

fp = open(r"C:\Users\sakth\Desktop\ASRS.txt", 'r')    
total_bytes = 0

while True:
    chunk = fp.read(1024)
    if chunk == '':
        print("File reached EOF")
        break
    print(chunk)
    total_bytes = total_bytes + len(chunk)

print("total bytes sent", total_bytes)

谁能解释一下为什么同一个文件会得到不同的大小?

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    您在 Windows 上,并且您的文件可能包含 204 (11264-11060) 回车换行对,在文本模式下读取时,它们被规范化为单个换行 (\n) 字符。使用二进制模式 ('rb') 避免这种转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2015-11-21
      • 2019-01-20
      相关资源
      最近更新 更多