1. 打开文件 - open()函数
使用open()
函数打开文件,基本语法:
file_object = open(file_path, mode, encoding="utf-8")
常用模式:
'r'
:读取模式(默认)'w'
:写入模式(覆盖现有内容)'a'
:追加模式'r+'
:读写模式'b'
:二进制模式(例如:'rb'或'wb')
文件IO(Input/Output)即文件输入输出,是编程中处理文件读写操作的核心概念。在Python中,文件IO操作使我们能够与计算机文件系统交互,包括:
Python通过内置的open()
函数和文件对象提供了一套简单而强大的文件操作接口。
使用open()
函数打开文件,基本语法:
file_object = open(file_path, mode, encoding="utf-8")
常用模式:
'r'
:读取模式(默认)'w'
:写入模式(覆盖现有内容)'a'
:追加模式'r+'
:读写模式'b'
:二进制模式(例如:'rb'或'wb')Python提供了多种读取文件内容的方法:
with open('example.txt', 'r') as file: content = file.read() print(content)
with open('example.txt', 'r') as file: line = file.readline() while line: print(line.strip()) # 使用strip()移除行尾换行符 line = file.readline()
with open('example.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip())
写入文件同样有多种方法:
with open('output.txt', 'w') as file: file.write("第一行内容\n") file.write("第二行内容\n")
lines = ["第一行\n", "第二行\n", "第三行\n"] with open('output.txt', 'w') as file: file.writelines(lines)
Python的with
语句是处理文件的最佳实践:
# 读取文件示例 with open('input.txt', 'r') as input_file: data = input_file.read() # 处理数据... # 写入文件示例 with open('output.txt', 'w') as output_file: output_file.write(data)
使用seek()
和tell()
方法管理文件指针:
with open('example.txt', 'r+') as file: # 读取前10个字符 print(file.read(10)) # 获取当前位置 position = file.tell() print(f"当前位置: {position}") # 移动到文件开头 file.seek(0) # 在当前位置写入内容 file.write("插入的内容")
with
语句处理文件os.path
模块处理路径分隔符os.path.exists(file_path)
Python文件IO操作是日常编程中的基础技能。掌握open()
函数、各种读写方法以及上下文管理,能够让你高效地处理文件操作任务。记住:
with
语句确保文件正确关闭通过本教程,你应该已经掌握了Python文件IO的核心概念和操作方法,可以开始在实际项目中应用这些技能了。
本文由HanTeng于2025-08-05发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://521pj.cn/20257347.html
发表评论