1. 使用open()函数打开文件在Python中,使用open()函数是访问文件的第一步。这个函数不仅能够打开文件,还能指定文件的访问模式(读取、写入、追加等)。以下是一个简单的例子: 打开一个文件...
open()函数打开文件在Python中,使用open()函数是访问文件的第一步。这个函数不仅能够打开文件,还能指定文件的访问模式(读取、写入、追加等)。以下是一个简单的例子:
# 打开一个文件用于读取
with open('example.txt', 'r') as file: content = file.read() print(content)在这个例子中,example.txt 是要打开的文件名,'r' 表示以只读模式打开文件。with语句确保文件在操作完成后会被正确关闭。
逐行读取文件是处理大文件时的常用技巧,可以避免一次性加载整个文件到内存中。
with open('large_file.txt', 'r') as file: for line in file: print(line, end='')readline()方法readline()方法可以一次读取文件的一行。
with open('example.txt', 'r') as file: line = file.readline() print(line, end='')readlines()方法readlines()方法可以读取文件的所有行,并返回一个列表。
with open('example.txt', 'r') as file: lines = file.readlines() for line in lines: print(line, end='')write()方法write()方法可以将字符串写入文件。
with open('output.txt', 'w') as file: file.write('Hello, World!')writelines()方法writelines()方法可以将字符串列表写入文件。
lines = ['Hello, ', 'World!']
with open('output.txt', 'w') as file: file.writelines(lines)使用a模式打开文件,可以在文件末尾追加内容。
with open('output.txt', 'a') as file: file.write('\nThis is an appended line.')Python提供了多种文件访问模式,包括:
r:只读模式w:写入模式,如果文件存在则会被覆盖x:创建模式,如果文件已存在则抛出异常a:追加模式,内容将被写入文件末尾b:二进制模式t:文本模式(默认)+:读写模式在文件操作中,错误处理非常重要。可以使用try...except语句来捕获并处理可能发生的异常。
try: with open('nonexistent.txt', 'r') as file: content = file.read() print(content)
except FileNotFoundError: print('The file does not exist.')
except IOError: print('An I/O error occurred.')通过以上五大技巧,你可以轻松地在Python中访问文件,无论是读取还是写入。掌握这些技巧,将有助于你在数据处理和文件管理方面更加高效。