当前位置:首页>python>【Python】Day18:文件读写与环境变量

【Python】Day18:文件读写与环境变量

  • 2026-10-11 07:33:26
【Python】Day18:文件读写与环境变量

🎯 学习目标

  1. 掌握文件的打开模式:r(读)、w(写)、a(追加)
  2. 学会用with open()安全地读写文件(自动关闭)
  3. 掌握read()、readline()、readlines()的区别
  4. 理解环境变量的作用,学会用python-dotenv管理敏感配置

一、文件读写基础

  1. 打开文件:open()函数
    # 语法f = open("文件名", "模式", encoding="编码")f.close()    # 必须关闭!
  2. 打开模式
    模式
    含义
    文件不存在时
    文件存在时
    r
    只读
    ❌ 报错
    读取内容
    w
    只写
    ✅ 创建
    清空重写
    a
    追加
    ✅ 创建
    末尾追加
    r+
    读写
    ❌ 报错
    覆盖写

二、with 语句:自动关闭文件(重要!)

  1. 为什么用with?
    # ✅ 推荐写法with open("hello.txt", "w", encoding="utf-8") as f:    f.write("Hello, World!\n")    f.write("第二行\n")# 离开 with 块,文件自动关闭,不需要 f.close()
    • 手动close()容易忘记(尤其在出错时)
    • with会在代码块结束后自动关闭文件,即使出错也会关闭

三、读取文件

  1. read():一次性读取全部内容
    with open("hello.txt", "r", encoding="utf-8") as f:    content = f.read()    print(content)
  2. readlines():按行读取,返回列表
    with open("hello.txt", "r", encoding="utf-8") as f:    lines = f.readlines()    print(lines)    # ["Hello, World!\n", "第二行\n"]
  3. 最常用:直接遍历文件对象
    with open("hello.txt", "r", encoding="utf-8") as f:for line in f:        print(line.strip())    # strip() 去掉换行符

四、环境变量与 python-dotenv

  1. 为什么需要环境变量?
    # ❌ 硬编码 API Key(危险!上传到 GitHub 就泄露了)API_KEY = "sk-abc123456789"# ✅ 从环境变量读取import osapi_key = os.environ.get("API_KEY")
  2. 用.env文件管理环境变量
    • 创建.env文件(如果上传代码到代码托管平台,如:github。一定要将该文件写入.gitignore):
      API_KEY=sk-abc123456789DB_HOST=localhostDB_PORT=5432
    • 用python-dotenv读取:
      pip install python-dotenv
      from dotenv import load_dotenvimport osload_dotenv()    # 加载 .env 文件api_key = os.getenv("API_KEY")db_host = os.getenv("DB_HOST", "127.0.0.1")  # 可设默认值print(f"API Key: {api_key}")

⚠️ 常见坑

  1. 写文件时忘记encoding="utf-8"
    # Windows 默认编码可能不是 UTF-8,会导致中文乱码with open("test.txt", "w", encoding="utf-8") as f:  # ✅    f.write("中文内容")
  2. w模式会清空原文件
    # 想在文件末尾添加内容,应该用 a 模式with open("log.txt", "a", encoding="utf-8") as f:   # ✅ 追加    f.write("新的日志\n")
  3. .env文件提交到 Git
    • 一定要把.env加入.gitignore!

✍️ 实战练习

  1. 日志记录器
    • 要求:写一个函数,将时间戳和消息写入日志文件。
    • 示例:
      from datetime import datetimedefwrite_log(message, filename="app.log"):    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")with open(filename, "a", encoding="utf-8") as f:        f.write(f"[{timestamp}] {message}\n")write_log("程序启动")write_log("用户登录")
  2. 配置管理
    • 要求:创建.env文件存储配置,用 Python 读取。
    • 示例:
      # .env# APP_NAME=MyApp# DEBUG=Truefrom dotenv import load_dotenvimport osload_dotenv()print(os.getenv("APP_NAME"))  # MyApp

✅ 自测清单

  • [ ] 能区分文件打开模式r、w、a 的区别
  • [ ] 能用with open()安全地读写文件,知道它会自动关闭
  • [ ] 知道读取文件的三种方式:read()、readlines()、遍历
  • [ ] 知道写文件时必须加encoding="utf-8"防止中文乱码
  • [ ] 理解环境变量的作用,能用python-dotenv管理 API Key

最新文章

随机文章