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

Day 24 - 文件、目录与路径 - Python学习笔记

Udemy - 100 Days of Code: The Complete Python Pro Bootcamp

Day 24 - Intermediate - Files, Directories and Paths

目录

        • 182. Add a High Score to the Snake Game
        • 183. Open, Read and Write Files
        • 184. Read and Write the High Score to a File
        • 185. Relative and Absolute File Paths
        • 186. Mail Merge Project

182. Add a High Score to the Snake Game

Snake Game 完整笔记

class Scoreboard(Turtle):  def __init__(self):  super().__init__()  self.score = 0  self.high_score = 0  self.color("white")  self.hideturtle()  self.penup()  self.goto(0, 260)  self.update_scoreboard()  def update_scoreboard(self):  self.clear()  self.write(f"Score: {self.score} High Score: {self.high_score}", align=ALIGNMENT, font=FONT)  def increase_score(self):  self.score += 1  self.update_scoreboard()  def reset(self):  if self.score > self.high_score:  self.high_score = self.score  self.score = 0  self.update_scoreboard()class Snake:...def reset(self):  for seg in self.segments:  seg.goto(1000, 1000)  self.segments.clear()  self.create_snake()  self.head = self.segments[0]# Detect collision with wall  
if (snake.head.xcor() > 280 or snake.head.xcor() < -280 or  snake.head.ycor() > 280 or snake.head.ycor() < -280):  scoreboard.reset()  snake.reset()  # Detect collision with tail  
for segment in snake.segments[1:]:  if snake.head.distance(segment) < 10:  scoreboard.reset()  snake.reset()
183. Open, Read and Write Files

读写文件

Open

  • open(file, mode='rt', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明
file:文件路径或文件描述符
mode:打开模式

  • "r" 读取模式(默认),"w" 覆盖模式,"a" 追加模式,"x" 独占创建
  • "t" 文本模式(默认),"b" 二进制模式
  • "+" 可读可写

buffering:缓冲策略

  • 0 无缓冲(仅二进制模式)
  • 1 行缓冲(仅文本模式)
  • >1 指定缓冲区大小(字节)
  • -1 系统默认缓冲策略

encoding:编码格式(仅文本模式)(如 utf-8,gbk,ascii)
errors: 编码报错方式(仅文本模式)(如 “strict” 直接报错, “ignore” 忽略错误字符, “replace” 替换成 �)
newline:换行符设置(仅文本模式)(None,“”,“\n”,“\r”,“\r\n”)

closefd:关闭文件时是否同时关闭底层文件描述符
opener:自定义打开器函数

Read

  • 读取文件:read(size=-1)
  • 按行读取:readline(size=-1)
  • 读取行列表:readlines(hint=-1)

Write

  • 写入文件:write(string)
  • 写入行列表:writelines(lines)
# Read Files
file = open("file.txt")    
print(file.read())    
file.close()  with open("file.txt") as file:  print(file.read())  with open("file.txt") as file:  print(file.readline())with open("file.txt") as file:  print(file.readlines())  with open("file.txt") as file:    for line in file:    print(line)# Write Files
with open("file.txt", "a") as file:  file.write("append")with open("file.txt", "w") as file:file.write("line 1\nline 2\nline 3\n")with open("file.txt", "w") as file:file.writelines(["line 1\n", "line 2\n", "line 3\n"])# Create Files
file = open("file.txt", "x") 
file = open("file.txt", "a") 
file = open("file.txt", "w") 
184. Read and Write the High Score to a File

Replit

class Scoreboard(Turtle):  def __init__(self):  super().__init__()  self.score = 0  try:with open("data.txt") as file:self.high_score = int(file.read())except FileNotFoundError:self.high_score = 0 self.color("white")  self.hideturtle()  self.penup()  self.goto(0, 260)  self.update_scoreboard()def update_scoreboard(self):  self.clear()  self.write(f"Score: {self.score} High Score: {self.high_score}", align=ALIGNMENT, font=FONT)  def increase_score(self):  self.score += 1  self.update_scoreboard()def reset(self):  if self.score > self.high_score:  self.high_score = self.score  with open("data.txt", "w") as file:  file.write(f"{self.high_score}")  self.score = 0  self.update_scoreboard()
185. Relative and Absolute File Paths
Root
└── Work├── app.log└── Project├── main.py├── file.txt└── assets└── img.png

Absolute File Path 绝对文件路径
Root Directory 根目录:/Work/Project/file.txt

Relative File Path 相对文件路径
Parent Directory 上级目录:../app.log
Same Directory 同级目录:./file.txt
Subdirectory 下级目录:assets/img.png

186. Mail Merge Project

Replit

"""
Dear [name],  You are invited to my birthday this Saturday.  Hope you can make it!  Angela
"""PLACEHOLDER = "[name]"  with open("./Input/Names/invited_names.txt") as names_file:  names = names_file.readlines()  with open("./Input/Letters/starting_letter.txt") as letter_file:  letter_contents = letter_file.read()  for name in names:  stripped_name = name.strip()  new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)  with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", "w") as completed_letter:completed_letter.write(new_letter)
http://www.dtcms.com/a/453298.html

相关文章:

  • 第9讲:函数递归——用“套娃”思维解决复杂问题
  • 东莞网站竞价推广运营百度云虚拟主机如何建设网站
  • 权限管理混乱微服务安全架构:OAuth2.0+JWT无感刷新方案非法请求拦截率
  • 北京理工大学网站开发与应用彩票网站开发彩票网站搭建
  • 网站建设公司重庆装修设计公司公司价格表
  • 厦门市建设局查询保障摇号网站首页系统开发板价格
  • 金溪网站建设制作电商系统开发公司
  • 直方图 vs 箱线图:两种看数据分布的思路差异
  • 构建AI智能体:五十六、从链到图:LangGraph解析--构建智能AI工作流的艺术工具
  • 【Spring】AOP的核心原理配方
  • 惠州建站平台建筑人才网招聘信息
  • 《Cargo 参考手册》第一章:清单
  • MVCC 多版本并发控制
  • 【AI智能体】Coze 打造AI数字人视频生成智能体实战详解:多模态情感计算与云边协同架构
  • 重庆网站建设培训机构学费重庆市官方网站
  • 关系建设的网站上海网站seo招聘
  • Vue router-view和router-link分开写在不同的组件中实现导航栏切换界面
  • Wan2.2-Animate V2版 - 一键替换视频角色,实现角色动作及表情同步迁移替换 支持50系显卡 ComfyUI工作流 一键整合包下载
  • Coordinate Attention for Efficient Mobile Network Design 学习笔记
  • 初识MYSQL —— 数据类型
  • 大型网站建设行情南通专业网站设计制作
  • 【AI智能体】Coze 打造AI数字人视频生成智能体实战详解:从0到1构建可交互虚拟主播
  • LabVIEW使用3D场景光照
  • 河北建设厅网站修改密码在哪wordpress 前台 很慢
  • 数字设计 综合工具 yosys 源码安装与应用简介
  • HikariCP 连接池完全指南
  • 绵竹网站建设大连装修公司
  • C++空值初始化利器:empty.h使用指南
  • 电子版康奈尔笔记写作方案对比
  • (3)SwiftUI 的状态之上:数据流与架构(MVVM in SwiftUI)