Python读取文本文件时readlines()返回空列表问题求助
解决文件read()后readlines()返回空列表的问题
这是因为文件对象的读取指针在你调用file.read()之后已经移动到了文件末尾,后续的任何读取操作都会从这个位置开始,自然获取不到内容。
解决方法:
重新打开文件:每次读取操作前重新打开文件,确保读取指针回到文件开头。推荐使用
with语句自动管理文件资源,避免手动关闭遗漏:with open(r'path\to\file.txt','r') as file: print(file.read()) with open(r'path\to\file.txt','r') as file: print(file.readlines())保存首次读取的内容:把
file.read()的结果存入变量,后续直接复用这个变量,无需重复读取文件。如果需要和readlines()一致的列表格式,可以用splitlines()转换:file = open(r'path\to\file.txt','r') content = file.read() print(content) # 转换为按行分割的列表 content_lines = content.splitlines() print(content_lines) file.close()重置读取指针:调用
file.seek(0)将指针移回文件开头,就能再次读取文件内容:file = open(r'path\to\file.txt','r') print(file.read()) # 重置指针到文件起始位置 file.seek(0) print(file.readlines()) file.close()
内容的提问来源于stack exchange,提问作者jackdoli64
相关产品推荐
相关产品推荐

