【问题标题】:I am having trouble reading what I have written in a txt file in Python [duplicate]我无法阅读我在 Python 中写入的 txt 文件中的内容 [重复]
【发布时间】:2021-07-25 10:31:13
【问题描述】:

我正在尝试检查文件是否存在。

import os.path
from os import path

if path.exists('file.txt'):
    f = open('file.txt', 'r+')
    f.write('Hello there!')
    f.close()
else:
    print('No file')

【问题讨论】:

  • 问题出在 open() 的第二个参数上。在当前模式 (r+) 下,任何新数据都会覆盖旧数据,从而将其删除。您必须将 'r+' 更改为 'a+' 才能以附加数据模式打开文件,而不是重写。

标签: django


【解决方案1】:

但是当我第二次打印文件时,它只打印出文件中已经存在的文本

不,它不会,您的第二次打印不会打印任何内容(或者只是一个空行)。

当您使用read() 读取文件对象时,您将移动到对象的末尾。与write 相同。如果要再次读取整个文件,则必须将使用seek(0) 读取的位置更改为文件对象中的第一个位置。

我已经稍微更改了您的代码以使用 with 语法,为您关闭文件:

import os.path
from os import path

if path.exists('file.txt'):
    with open('file.txt', 'r+') as f:
        contents = f.read()
        print(contents)
        f.write('Hello there!')
        f.seek(0) # <-- go back to position 0
        new_content = f.read()
        print(new_content)
else:
    print('No file')

假设您的文件内容最初是ABC\n,这将打印:

ABC

ABC
Hello there!

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2014-01-23
    • 2020-04-17
    相关资源
    最近更新 更多