【问题标题】:Python - Open Read/Write ErrorPython - 打开读/写错误
【发布时间】:2014-08-29 12:20:32
【问题描述】:

我已经查看了很多答案,但没有一个对我有帮助。我需要一个代码,如果文件不存在,则创建然后打开以进行读写。代码能写不能读,是什么问题?

>>> `file = open('test.txt', 'w+')`
>>>  file.write('this is a test')
14
>>>  file.read()
''
>>>

【问题讨论】:

    标签: python windows file operating-system


    【解决方案1】:

    在尝试读取文件之前,您必须先找到文件的开头。

    >>> _file = open('test.txt', 'w+')
    >>> _file.write('this is a test')
    14
    >>> _file.read()
    ''
    >>> _file.seek(0)
    0
    >>> _file.read()
    'this is a test'
    >>> 
    

    0 表示文件的开头。 您可以拨打_file.tell()获取当前位置 您可以以编程方式将_file.tell_file.seek(offset, fromwhat) 结合起来。

    另外,使用内置的(文件)作为变量名也是不好的做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-08
      • 1970-01-01
      • 2015-08-22
      • 2023-03-06
      • 1970-01-01
      • 2017-12-15
      • 2014-01-06
      • 2013-08-19
      相关资源
      最近更新 更多