如何打开文件进行读写操作?

2024-04-20 13:01:42 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

我试过这样的方法,效果如期而至:

f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()

其中:

f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.

以及:

f.write(string) writes the contents of string to the file, returning None.

另外,如果打开Python tutorial about reading and writing files,您会发现:

'r+' opens the file for both reading and writing.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.

下面介绍如何在不关闭和重新打开的情况下读取文件,然后对其进行写入(覆盖任何现有数据):

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

r+是同时进行读写的规范模式。这与使用fopen()系统调用没有区别,因为file()/open()只是这个操作系统调用的一个小包装。

相关问题 更多 >