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

学习Python编程7,文件

打开读取文件

file = open('example.txt', 'r') data = file.read() print(data)

一行一行读取

file = open('example.txt', 'r') for line in file: print(line)

错误异常处理

try: file = open('example.txt', 'r') except FileNotFoundError: print("File not found!")

模式

'r',读,读取存在的文件。

'w',写,写入,如果文件不存在则创建新文件,存在则覆盖。

'a',追加写入,在文件尾追加写入,如果文件不存在则创建新文件。

'b',二进制。写入或读写二进制数据,如图片或音频文件。

写模式

file = open('example.txt', 'w') # Write to the file file.write('Hello, World!') # Close the file file.close()

读模式

file = open('example.txt', 'r') # Read the file contents content = file.read() # Print the contents print(content) # Close the file file.close()

文件删除

import os os.remove("example.txt")

文件重命名

import os os.rename("example.txt", "new_example.txt")

文件复制

import shutil shutil.copy("example.txt", "new_example.txt")

文件移动

import shutil shutil.move("example.txt", "/path/to/new_folder/example.txt")

读文件

file = open("example.txt", "w") content = file.read() line = file.readline() file.close()

写文件

file = open("example.txt", "w") file.write("Hello, World!") lines = ["Line 1", "Line 2", "Line 3"] file.writelines(lines) file.close()

关闭文件

file = open("example.txt", "w") # Perform operations on the file file.close()

获取文件大小

import os file_path = "example.txt" try: file_size = os.path.getsize(file_path) print("File size:", file_size, "bytes") except FileNotFoundError: print("File not found.")
import os file_path = "example.txt" try: file_stats = os.stat(file_path) file_size = file_stats.st_size print("File size:", file_size, "bytes") except FileNotFoundError: print("File not found.")

扩展名

import os filename = "example.txt" extension = os.path.splitext(filename)[1] print("File Extension:", extension)

判断文件是否存在

import os # Define the path of the file to check file_path = "/path/to/file" # Check if the file exists if os.path.exists(file_path): print("File exists!") else: print("File does not exist.")
import os # Define the path of the file to check file_path = "/path/to/file" try: # Check if the file exists with open(file_path) as f: print("File exists!") except FileNotFoundError: print("File does not exist.")

创建简单文件

with open("example.txt", "w") as file: print("Hello, World!", file=file)
with open("example.txt", "w") as file: file.write("Hello, World!")
http://www.jsqmd.com/news/1214087/

相关文章:

  • godirwalk最佳实践:内存优化、错误处理与并发控制技巧
  • 【Bug已解决】Macos 27 beta3 cannot submit task 解决方案
  • 2026乌兰察布甲醛治理怎么选:只做治理、不做检测的专业CMA 资质实验室——艾尚安醛甲醛治理中心室内空气及环境治理 - 创达咨询
  • USBCopyer:5个场景告诉你,为什么你需要这个U盘自动备份神器
  • ZygiskFrida常见问题排查与优化:从注入失败到稳定Hook
  • WarcraftHelper终极指南:魔兽争霸3性能优化与兼容性修复完整教程
  • 字典与哈希表:LeetCode两数之和与频率统计高效解法终极指南
  • 市监科普:哈尔滨黄金出手谨防 “高报价低结算”,称重、验金环节注意要点汇总 - 生活商业速报
  • 基于大语言模型的Web自动化框架Stagehand:原理、实战与优化
  • 我让AI查资料,结果在会上念了假数据翻车了
  • 【Bug已解决】Codex App: new task creation times out when configured MCP server is unreachable 解决方案
  • Wpomniagent(WP 万灵智体)首个正式版发布
  • Diablo Edit2:终极游戏角色编辑器完整指南
  • Fastfetch终极指南:5分钟掌握系统信息监控神器
  • 2026安顺筑宅安房屋修缮|全域防水补漏一站式服务,根治雨季渗漏难题 - 筑宅安
  • OBS Studio多机位直播终极指南:5步打造专业级直播体验
  • 即梦AI人物生成翻车预警(面部畸变/手部错误/光影失真),8类典型故障诊断表
  • Atmosphère系统架构深度解析与模块化配置实战指南
  • 安卓逆向实战:从静态分析到动态调试的完整技术解析
  • Python TDD实战:红绿重构循环驱动高质量代码开发
  • 2026四平装饰高性价比品牌排行综合参考指南 - 奔跑123
  • 暗黑3自动化助手:告别重复操作,专注游戏策略
  • 揭秘GPT-4 Turbo vs Claude 3.5 vs Qwen2.5:谁真正扛得住200K tokens?实测RAG响应衰减率与语义连贯性(附Benchmark原始数据)
  • 终极指南:5分钟上手iFakeLocation - iOS虚拟定位神器
  • OpenCV imgproc模块深度解析:从C++图像处理基础到高级优化实战
  • 沈阳迪奥包包回收价格实测曝光:走访五家门店,谁报价没套路出价高? - 奢侈品回收评测
  • Guns项目API文档:Swagger集成与RESTful接口设计规范
  • 大连卖黄金踩坑亏哭!逸程回收全流程透明,靠谱商家没有任何暗地扣费 - 融媒生活
  • BlackHole音频驱动终极指南:5步实现macOS零延迟音频路由
  • 3种创新方案彻底解决Umi-OCR离线文字识别工具下载难题