F

在 Python 中,当以写模式 ('w') 打开文件时,文件指针会自动指向文件开头,并且会清空文件内容。这意味着你无法在同一个文件句柄中进行读取操作,因为文件指针已经不在读取的位置。

解决方法:

  • 关闭文件句柄并重新打开:

    file = open('my_file.txt', 'w')
    file.write('Hello world!')
    file.close()
    file = open('my_file.txt', 'r')
    content = file.read()
    file.close()
    
  • 使用 'a' 模式追加写入:

    file = open('my_file.txt', 'a')
    file.write('Hello world!')
    file.seek(0)  # 将文件指针移到文件开头
    content = file.read()
    file.close()
    
  • 使用 'r+' 模式:

    file = open('my_file.txt', 'r+')
    file.write('Hello world!')
    file.seek(0)  # 将文件指针移到文件开头
    content = file.read()
    file.close()
    

注意:

  • 确保在操作文件完成后,使用 file.close() 关闭文件句柄以释放资源。
  • 使用 'r+' 模式时,文件指针会指向文件开头,因此需要使用 file.seek() 将文件指针移到想要读取的位置。
Python 文件操作:写模式下无法读取数据

原文地址: https://www.cveoy.top/t/topic/oslK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录