网站首页 > 基础教程 正文
Python的文件操作主要包括打开、读取、写入和关闭文件。你可以使用open()函数来打开文件,指定模式(如'r'读取,'w'写入)。读取文件可用read()、readline()或readlines(),写入则用write()或writelines()。
下面是一些Python文件操作的实战示例,涵盖读取、写入和处理文件的基本操作。
1. 写入文件
# 写入数据到文件
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a file operation example.")
2. 读取文件
# 读取文件内容
with open('example.txt', 'r') as file:
content = file.read()
print(content)
3. 按行读取文件
# 按行读取文件
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() 去掉行末的换行符
4. 追加内容到文件
# 追加内容到文件
with open('example.txt', 'a') as file:
file.write("\nAppending a new line.")
5. 读取所有行到列表
# 将所有行读取到列表
with open('example.txt', 'r') as file:
lines = file.readlines()
print(lines) # 每一行是列表中的一个元素
6. 处理文件异常
# 处理文件操作异常
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("文件未找到,请检查文件名或路径。")
猜你喜欢
- 2024-11-01 关于Python字符串的那些事 python字符串常见操作
- 2024-11-01 Python如何去掉字符串中不需要的字符
- 2024-11-01 一文掌握Python 中的文件处理 python对文件处理
- 2024-11-01 Python对文件的操作及对异常的处理
- 2024-11-01 如何将python脚本打包成exe文件 py脚本转exe
- 2024-11-01 站长在线:Python中去除字符串中的空格和特殊字符的4个方法详解
- 2024-11-01 python中字符串类型 python字符串常用的五种方法
- 2024-11-01 Python中pandas.Series.str.strip()数据处理方法的理解
- 2024-11-01 进入Python的世界04-字符串处理 python字符串处理函数有哪些
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)