如何打开文件进行读写? [英] How to open a file for both reading and writing?

查看:90
本文介绍了如何打开文件进行读写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以打开文件进行读写?

Is there a way to open a file for both reading and writing?

作为一种解决方法,我打开文件进行写入,将其关闭,然后再次打开以进行读取.但是,有没有一种方法可以打开和读取 的文件?

As a workaround, I open the file for writing, close it, then open it again for reading. But is there a way to open a file for both reading and writing?

推荐答案

在这里,您无需关闭并重新打开即可读取文件,然后写入文件(覆盖现有数据):

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

这篇关于如何打开文件进行读写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆