You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python写入文件后直接read()读取返回空值问题排查

问题根因

写入完成后直接读取返回空,是文件指针位置导致的:
Python对打开的文件会维护一个随读写移动的位置指针,你用w+模式打开clear_data.csv并执行所有write()操作后,指针最终停在整个文件的末尾位置。此时直接调用read(),会从当前指针位置(文件末尾)向后读取内容,自然只能拿到空字符串。
手动打开本地文件能看到正确处理后的内容,是因为本地打开文件时指针默认从文件起始位置开始加载,和代码中写入完成后的指针状态完全不同。

修复方法

方案1:写入完成后重置指针位置再读取

在读取操作前调用seek(0)将文件指针移动到文件起始位置即可,修改后核心代码如下:

with open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\data.csv","r+") as fi,\
        open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\clear_data.csv","w+") as fo:
    fi_reader=fi.readlines()  
    for line in fi_reader:
        line=line.replace(" ","")
        fo.write(line)  
    # 指针移回文件开头
    fo.seek(0)
    fo_reader=fo.read()
    print("the result of fo is here:",fo_reader)

方案2:写入完成关闭文件后重新打开读取

如果不需要在文件打开状态下同时完成读写,可以等写入逻辑执行完毕、with上下文管理器自动关闭文件后,再单独打开目标文件读取,这种方式不需要手动操作指针,逻辑更不容易出错:

# 仅执行写入逻辑
with open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\data.csv","r", encoding="utf-8") as fi,\
        open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\clear_data.csv","w", encoding="utf-8") as fo:
    for line in fi.readlines():
        fo.write(line.replace(" ", ""))

# 重新打开文件读取内容
with open("D:\\Users\\Documents\\Documents\\pythonFile\\PracticeAboutPython123\\resource\\clear_data.csv","r", encoding="utf-8") as fo:
    fo_reader = fo.read()
    print("the result of fo is here:",fo_reader)

提示:非必要不使用r+/w+这类读写混合模式,纯读用r、纯写用w可以规避绝大多数文件指针位置导致的异常。

内容的提问来源于stack exchange,提问作者Hol Horse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 04:57:10