首页 > 解决方案 > Python len(file.read()) != C# System.IO.File.ReadAllText(path).Length

问题描述

我尝试使用 C# 将 rgb 像素矩阵保存在文件中并在 python 中读取它。如果我的图像是 243*507,那么文件的 len 必须是 (height * width * rgb),然后是 243*507*3(我将每个 rgb 值保存为文件中的一个字节)。当我用 C# 阅读这个文件时,它有很好的 len (369603),它工作得很好。但是使用 python,我得到 369570 或另一个文件,多一点或少一点。当我读取文件时,它总是在 python 字符串中丢失字节。要获取图像文件,请下载python 中的frame.txt

代码:

f = open(path, "r")
if f.mode != 'r':
    print_cerror("Can't read file")
contents = f.read()
f.close()
print(len(contents) # Not the good len

C# 中的代码:

if (File.Exists(file_path))
{
    string text = System.IO.File.ReadAllText(file_path);
    Debug.Log("READ LEN = " + text.Length); // Perfect 369603 !
}

编辑:当我尝试使用“rb”时,文件的大小是 477537 而不是 369603。我认为它有一个标题或其他信息。我怎样才能只得到文件的正文?我尝试使用 seek(0, 1, 2) 但它只跳过 0, 1, 2 个第一个字节...

好的问题解决了:我的错,我用 C# 将字节写为文本然后文件不好 x) 抱歉

标签: c#pythonfile

解决方案


如果您想要以字节为单位的文件大小,您可以使用

import os
print(os.stat(path).st_size)

推荐阅读