当前位置: 首页 > news >正文

[python]非零基础上手之文件操作

这个其实很像Node.js.

读取操作:

with open ('./xx.txt', 'r', encoding = 'utf -8') as file:
for i in file:print(i)
#"file"是个变量, 名称自定, 参数2代表'read', 表明为读取操作.

追加操作:

属于写入的一种,不会重写文档,在原有内容后添加.

with open('./xx.txt', 'a+', encoding = 'utf-8') as file:file.write('写入内容')

何为with:

是一种上下文管理器, with语句管理的代码块执行完毕时, 会自动关闭文件, 这是受推荐的方法,可以确保文件使用完毕后正确关闭. 当然,也可以调用文件对象的close()手动关闭:
可以在读取结构中安插try/finally结构,因为我们也不知道能不能读取成功:

file = open('xx.txt', 'r')
try:file_content = file.read()print(file_content)
finally:file.close()

写入操作:

重写所有内容.

with open('example.txt', 'w') as file:file.write('HelloWorld')

写入json:

需要额外模块.

import json
json_file_path = 'example.json'
data = { 'name': 'John Doe', 'age': 30 }with open(json_file_path, 'w')
json.dumps(data) # json对象转字符串

文件重命名:

import os
files = os.listdir('path-to-directory') # 获取目录中文件列表
for file in files:	full_path = os.path.join('path-to-directoro', pythonif os.path.isfile(full_path) # 检测文件是否存在new_filename = 'new_name'os.rename(full_path, os.path.join('path_to_directory', new_filename)) # 旧路径, 新路径

逐行读文件_获取全部行:

with open('file.txt', 'r') as file:lines = file.readlines()print(lines[0])

逐行读文件_获取单行:

with open('file.txt', 'r') as file:line0 = file.readline()line1 = file.readline()

创建文件:

import os
if not os.path.exists('./aa.txt'):
try:with open('./aa.txt', 'w') as file
except IOError as error:print (error)

创建目录:

import os
if not os.path.exists('./aadir'):
try:os.makedirs('./aadir')
except IOError as error:print (error)

删除文件:

import os
if os.path.isfile('./aa.txt')
try:os.remove('./aa.txt')
except OSError as error:print(error)
http://www.xdnf.cn/news/282709.html

相关文章:

  • JAVA:使用 MapStruct 实现高效对象映射的技术指南
  • AI功能测试源码AI聊天AI视觉AI图像AI视频AI画外音写作助手AI测试多语言无加密源码
  • 第20节:深度学习基础-反向传播算法详解
  • Linux环境下的进程创建-fork函数的使用, 进程退出exit和_exit的区别,以及进程等待waitpid和status数据的提取方法
  • 一款免费的现场大屏幕知识竞赛抢答软件
  • SpringBoot校园失物招领平台源码开发实现
  • 永磁同步电机无速度算法--基于ESO-PLL的永磁同步电机无位置传感器控制
  • 适配器模式(Adapter Pattern)
  • 内容中台的AI中枢是什么?
  • LeetCode 热题 100 48. 旋转图像
  • lombok详解
  • cline或业务系统集成n8n的工作流(MCP Server Trigger、Call n8n Workflow Tool node)
  • 【力扣刷题记录】hot100错题本(一)
  • MySQL--索引精通详解
  • QT6(33)4.6滑动组件QSlider 与QProgressBar:理论,例题的界面搭建,与功能的代码实现
  • PATHWAYS: 用于机器学习的异步分布式数据流
  • Python Cookbook-6.20 精确和安全地使用协作的超类调用
  • 【AI提示词】黑天鹅模型专家
  • 从图文到声纹:DeepSeek 多模态技术的深度解析与实战应用
  • 气泡图、桑基图的绘制
  • Sway初体验
  • 微软Phi-4-reasoning技术报告解读
  • HTML基础1-元素与页面的结构
  • “链式前向星”等三种存图方式分别输出“无向无权图”的“DFS序列”
  • ABC404E 题解
  • 2025牛客五一集训派对day4
  • 纯继电器电路控制小车自动往复运动
  • (39)VTK C++开发示例 ---选择区域
  • MFiX(Multiphase Flow with Interphase eXchanges)软件介绍
  • 5块钱的无忧套餐卡可以变成流量卡吗