python - 为什么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?
解决方案
您以文本模式打开文件,该\r\n
文件将文件转换\n
为f.read()
. 有4行,匹配不一致。
以二进制模式打开它,你会得到一致的结果。
file_mode = "rb"
推荐阅读
- python - 如何选择在 Pandas 中使用 groupby 首次出现值的行以及随后出现的第一次
- php - 插入多行记录 Codeignite
- c++ - 通过 const 引用传递向量时出现 Intellisense 错误(但项目构建)
- java - 如何停止触发警报的响铃?
- r - r计算数据框中多列的综合得分和可靠性
- c++ - 使用 reinterpret_cast 以外的方法从地址以十六进制格式获取整数
- r - 如果列包含特定值,则将列名分配为单元格值
- c++ - 为什么运算符重载需要引用?
- javascript - 当我删除或拼接数组上的元素时,有什么方法可以停止触发深度监视?
- python - TypeError:“模块”对象不可下标(Python)