在Python中,文件处理是一项基本且常用的任务。Python标准库提供了丰富的文件处理函数和模块,使得读写文件变得相对简单。以下是一些常用的文件处理函数和它们的基本用法。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):打开文件,并返回文件对象。
file.read([size]):读取文件内容。
file.write(s):向文件写入内容。
file.close():关闭文件。
示例代码:
| # 使用with语句打开文件
with open('example.txt', 'w') as file: # 以写入模式打开文件 'example.txt' file.write('Hello, world!\n') # 向文件写入一行文本 'Hello, world!' 并换行 file.write('This is another line.') # 向文件写入另一行文本 # 读取文件内容 with open('example.txt', 'r') as file: # 以读取模式打开文件 'example.txt' content = file.read() # 读取文件的全部内容并存储在变量 content 中 print(content) # 输出文件内容 # 逐行读取 with open('example.txt', 'r') as file: # 以读取模式打开文件 'example.txt' for line in file: # 遍历文件的每一行 print(line, end='') # 打印每一行,end='' 参数用于去掉行尾的换行符 |
代码效果:
| Hello, world!
This is another line. Hello, world! This is another line. |
24