在 Python 中,文件对象(File Object)提供了一系列方法用于对文件进行操作。以下是一些常用的文件方法:

1. file.read(size=-1)

从文件中读取指定大小的字节,默认为读取整个文件。返回一个字符串对象。
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

2. file.readline(size=-1)

从文件中读取一行,可以指定读取的最大字节数。返回一个字符串对象。
with open("example.txt", "r") as file:
    line = file.readline()
    print(line)

3. file.readlines(hint=-1)

从文件中读取多行,可以指定读取的最大字节数。返回一个包含多行的列表。
with open("example.txt", "r") as file:
    lines = file.readlines()
    print(lines)

4. file.write(string)

向文件中写入字符串。返回写入的字符数。
with open("example.txt", "w") as file:
    file.write("Hello, this is a sample text.")

5. file.writelines(lines)

向文件中写入字符串列表。
with open("example.txt", "w") as file:
    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    file.writelines(lines)

6. file.flush()

刷新文件缓冲区,将缓冲区中的数据立即写入文件。
with open("example.txt", "w") as file:
    file.write("Hello")
    file.flush()  # 立即写入文件

7. file.seek(offset, whence=0)

移动文件指针到指定位置。offset 指定偏移量,whence 指定相对位置,默认为 0(文件开头)。
with open("example.txt", "r") as file:
    file.seek(5)  # 移动到文件第6个字节的位置
    content = file.read()
    print(content)

8. file.tell()

返回当前文件指针的位置。
with open("example.txt", "r") as file:
    position = file.tell()
    print(f"Current position: {position}")

这些是文件对象常用的一些方法,你可以根据实际需要选择适当的方法进行文件操作。


转载请注明出处:http://www.zyzy.cn/article/detail/13331/Python 基础