一旦文件被打开,我们就可以使用不同的方法来读取文件的内容。

2.1 读取整个文件

使用read()方法可以读取整个文件的内容。

with open('example.txt', 'r') as file: 
    content = file.read() 
    print(content)
2.2 逐行读取

使用readline()方法可以逐行读取文件的内容。

with open('example.txt', 'r') as file: 
    line = file.readline() 
    while line: 
        print(line) 
        line = file.readline()
2.3 读取所有行

使用readlines()方法可以将文件的所有行读取到一个列表中。

with open('example.txt', 'r') as file: 
    lines = file.readlines() 
    for line in lines: 
        print(line)
3. 写入文件内容

使用打开文件时的不同模式,可以实现写入文件的不同方式。

3.1 写入单行

使用write()方法可以向文件中写入指定内容。

with open('example.txt', 'w') as file: 
    file.write('Hello, World!\n')
3.2 写入多行

使用writelines()方法可以将多行内容写入文件。

lines = ['Line 1\n', 'Line 2\n', 'Line 3\n'] 
with open('example.txt', 'w') as file: 
    file.writelines(lines)
4. 文件迭代器

文件对象是可迭代的,因此我们可以使用for循环逐行读取文件内容。

with open('example.txt', 'r') as file: 
    for line in file: 
        print(line)
5. 上下文管理器(Context Manager)

使用with语句打开文件,可以确保在文件使用完毕后自动关闭文件,避免资源泄漏。

with open('example.txt', 'r') as file: 
    content = file.read() 
    print(content) # 文件自动关闭
6. 异常处理

在文件读写过程中,可能会出现异常,例如文件不存在或权限错误。因此,在操作文件时,最好使用异常处理来增强程序的健壮性。

try: 
    with open('example.txt', 'r') as file: 
        content = file.read() 
        print(content) 
except FileNotFoundError: 
    print('文件不存在!') 
except PermissionError: 
    print('无权限访问文件!') 
except Exception as e: 
    print(f'发生未知错误:{e}')
7. 关闭文件

虽然使用with语句可以确保文件被正确关闭,但在某些情况下,可能需要手动关闭文件。

file = open('example.txt', 'r') 
content = file.read() 
print(content) 
file.close() # 手动关闭文件
8. 二进制文件操作

在处理二进制文件时,打开文件时需要指定'b'模式。

with open('example.jpg', 'rb') as file: 
    data = file.read() # 对二进制数据进行操作
9. 文件定位

在文件读写中,有时候需要移动文件指针的位置,可以使用seek()方法。

with open('example.txt', 'r') as file: 
    content = file.read(10) # 读取前10个字符 
    print(content) 
    file.seek(0) # 移动文件指针到文件开头 
    content = file.read(5) # 再次读取前5个字符 
    print(content)
10. 总结

文件读写是编程中常见的操作之一,Python提供了简单而强大的工具来处理文件。通过了解文件的打开、读取、写入等基本操作,以及一些常见的技巧和最佳实践,你可以更加灵活地应对各种文件操作需求。使用上下文管理器和异常处理,可以使代码更加健壮,防止因文件操作引起的问题。在实际应用中,根据具体需求选择适当的方法和模式,可以更好地完成文件处理任务。