首页 > 解决方案 > 为什么Python文件处理中文件的总大小和指针的当前位置有冲突?

问题描述

我的文件内容如下:

1   2   
34
56
78

下面是我写的代码:

file_name = "abc.txt"
file_mode = "r"
with open(file_name, file_mode) as f:
    my_list = list(f.read())
    print(my_list)
    print("length of the file is", len(my_list))
    print("position being told by .tell() method is", f.tell())

代码输出:

['1', '\t', '2', '\t', '\n', '3', '4', '\n', '5', '6', '\n', '7', '8', '\n']
length of the file is 14
position being told by .tell() method is 18

你知道这里有什么问题吗?为什么当我的文件内容的总长度不超过14时,tell方法返回指针的位置为18?

标签: pythonpython-3.x

解决方案


您以文本模式打开文件,该\r\n文件将文件转换\nf.read(). 有4行,匹配不一致。

以二进制模式打开它,你会得到一致的结果。

file_mode = "rb"

推荐阅读