网站首页 > 技术文章 正文
引言:
Python中,对.txt后缀的文件进行多种操作。以下是一些常见的操作及其示例代码:
先让我们来学习一下文件的打开模式及其作用:
读取整个文件:
path =r'D:\file.txt' #todo txt文件所在的路径
with open(path, 'r') as file:
content = file.read()
print(content)
逐行读取:
path =r'D:\file.txt' #todo txt文件所在的路径
with open(path, 'r') as file:
lines = file.readlines()
print(lines) #todo 打印的结果列表展示每一行内容
按行迭代读取:
path =r'D:\file.txt' #todo txt文件所在的路径
with open(path, 'r') as file:
for line in file:
print(line, end='')
with open(path, 'r') as file:
for _ in range(6): # todo 读取指定的行,如前6行
line = file.readline()
print(line, end='')
覆盖写入(如果文件不存在则创建,如果文件存在则先清除文件内容并写入新的内容):
path =r'D:\file.txt' #todo txt文件所在的路径
with open(path 'w') as file:
file.write('Hello, World!\n')
追加写入:
path =r'D:\file.txt' #todo txt文件所在的路径
with open(path, 'a') as file:
file.write('你好呀\n')
删除指定行:在内存中处理数据
path = r'D:\file.txt' #todo 替换为你的实际文件路径
line_to_remove = 3 #todo 要删除的行号(1-based)
try:
with open(path, 'r') as file:
lines = file.readlines()
#todo 删除指定行(减去 1 因为 list 是 0-based 索引)
if 1 <= line_to_remove <= len(lines):
del lines[line_to_remove - 1]
else:
print(f"行号 {line_to_remove} 超出文件范围。")
with open(path, 'w') as file:
file.writelines(lines)
except FileNotFoundError:
print(f"文件 {path} 不存在。")
except Exception as e:
print(f"发生错误: {e}")
检查文件是否存在:
import os
path =r'D:\file.txt' #todo txt文件所在的路径
if os.path.exists(path):
print('File exists.')
else:
print('File does not exist.')
删除文件:
import os
path =r'D:\file.txt' #todo txt文件所在的路径
if os.path.exists(path):
os.remove(path)
print('File deleted.')
else:
print('File does not exist.')
重命名文件:
import os
path =r'D:\file.txt' #todo txt文件所在的路径
path_file= r'D:\new_file.txt'
os.rename(path, path_file)
批量重命名文件:
import os
directory = r'D:\test'
for filename in os.listdir(directory): #todo 将D:\test目录下所有以.txt结尾的文件,重新命名
if filename.endswith('.txt'):
new_name = filename.replace('.txt', '_old.txt')
os.rename(os.path.join(directory, filename), os.path.join(directory, new_name))
获取文件大小:
import os
path =r'D:\file.txt'
file_size = os.path.getsize(path) #todo 获取文件大小
print(f'File size: {file_size} bytes')
读取和写入二进制文件:
path =r'D:\file.txt'
with open(path, 'rb') as file: #todo 读取二进制文件
binary_data = file.read()
with open(path, 'wb') as file: #todo 写入二进制数据
file.write(binary_data)
文件锁定(进程间的互斥访问):
import fcntl
path =r'D:\file.txt'
with open(path, 'r+') as file:
fcntl.flock(file, fcntl.LOCK_EX) #todo 锁定文件
fcntl.flock(file, fcntl.LOCK_UN) #todo 解锁文件
逐块读取大文件:
chunk_size = 1024 #todo 定义块大小
path =r'D:\large_file.txt'
with open(path, 'r') as file:
while chunk := file.read(chunk_size):
process(chunk) #todo 对每个块进行处理
处理文件编码:
path =r'D:\file.txt'
#todo 以特定编码读取文件
with open(path, 'r', encoding='utf-8') as file:
content = file.read()
#todo 以特定编码写入文件
with open(path, 'w', encoding='utf-8') as file:
file.write('Some content')
文件内容比较:
import filecmp
result = filecmp.cmp('file1.txt', 'file2.txt')
if result:
print("Files are identical")
else:
print("Files are different")
图文说明如下:

- 上一篇: python的print命令
- 下一篇: PyInstaller/Python代码的加密编译与反编译
猜你喜欢
- 2024-12-25 小白必备:如何用auto-py-to-exe轻松打包 Python 脚本
- 2024-12-25 Python3基础之构建setup.py
- 2024-12-25 加密Python源码方案 PyArmor
- 2024-12-25 PyInstaller/Python代码的加密编译与反编译
- 2024-12-25 python的print命令
- 2024-12-25 探秘PyMySQL:你可能错过的宝藏Python库
- 2024-12-25 深入探秘py_compile:你可能错过的Python宝藏
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)