【问题标题】:Cannot open file in write mode after copyfile复制文件后无法以写入模式打开文件
【发布时间】:2020-04-05 22:11:09
【问题描述】:

我需要编辑刚刚使用copyFile() 创建的文件。

但是,如果在'w' 模式或'w+''a' 模式下打开文件,readlines() 总是会失败。

copyfile(fileObj.file_to_open, fileObj._copyToFileName)
    with open(fileObj._copyToFileName, 'w') as thisFile:
        lines = thisFile.readlines()

如果我将其保留为默认模式(读取模式),我可以readlines()

为什么使用写入模式打开会成为问题?

【问题讨论】:

  • 你以write mode打开文件,你需要以read mode打开它,这意味着:with open(fileObj._copyToFileName, 'r') as thisFile:

标签: python readlines


【解决方案1】:

您正在寻找 r+a+ 模式,它允许对文件 (see more) 进行读写操作。

使用r+,位置最初位于开头,但读取一次会将其推向末尾,允许您追加。对于a+,位置最初位于末尾。

使用f.seek(0),您可以将阅读位置移到开头。

with open("filename", "r+") as f:
    text = f.read()    
    f.seek(0)
    # reread if required here

【讨论】:

    【解决方案2】:

    当您以写入模式打开文件时,Python 会截断该文件。如果你想在没有这个的情况下打开文件进行读/写,你需要使用open(filename, 'r+')

    还要确保跟踪光标在文件中的位置,因为您可能会覆盖数据。使用file.seek(offset) 来控制它。

    查看the Python open documentation了解更多详情。

    【讨论】:

    • 感谢您的回复。但是如果我用 r+ 模式打开文件,我就无法编辑/写入文件
    猜你喜欢
    • 2016-10-21
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多