Python学习(1) ----- Python的文件读取和写入

发布于:2025-05-28 ⋅ 阅读:(21) ⋅ 点赞:(0)

这篇文章主要用于备忘录,记录一下Python中的文件读取和写入,以及用到的相对路径和绝对路径。

一、文件的读取

在 Python 中,读取文件有几种常用方式,适合不同的应用场景。以下是最常见的读取方式以及对应的代码实例:


📄 假设我们有一个文件 example.txt,内容如下:

Hello world
This is a sample file.
Python is great!

✅ 1. 逐行读取:使用 for line in file

with open("example.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip 去除换行符
  • 适用场景:处理大文件时,节省内存。
  • 每次读一行,效率高。

✅ 2. 读取全部内容read()

with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)
  • 适用场景:需要一次性获取整个文件内容。
  • 注意:大文件时内存占用高。

✅ 3. 读取所有行到列表readlines()

with open("example.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())
  • 返回值:每一行是列表中的一个元素(含换行符)。
  • 适用场景:需要索引具体某几行。

✅ 4. 读取固定长度的字符read(n)

with open("example.txt", "r", encoding="utf-8") as f:
    first_10 = f.read(10)
    print(first_10)
  • 读取前 10 个字符
  • 适合:处理二进制数据或大文件的分段读取。

🧠 小贴士:

  • "r":只读(默认)。
  • "rb":以二进制模式读。
  • "r+":读写。
  • 一般推荐加上 encoding="utf-8" 来避免编码问题。
  • 使用 with open(...) as f: 可以自动关闭文件,防止资源泄露。

二、文件的写入

在 Python 中,文件写入是通过 open() 函数与写入模式(如 "w""a""w+" 等)配合使用的。以下是常用写入方式的详细介绍和示例。


📌 常见写入模式

模式 含义 是否会覆盖原文件 文件不存在时
"w" 写入(write) ✅ 是,会清空文件 ✅ 创建新文件
"a" 追加(append) ❌ 否,追加到末尾 ✅ 创建新文件
"w+" 写入 + 读取 ✅ 是 ✅ 创建新文件
"a+" 追加 + 读取 ❌ 否 ✅ 创建新文件

✅ 1. 写入内容到文件(覆盖原内容)

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, world!\n")
    f.write("Python is awesome.\n")
  • 每次运行都会清空原文件并重新写入
  • 没有文件会创建文件

✅ 2. 追加内容到文件末尾

with open("output.txt", "a", encoding="utf-8") as f:
    f.write("New line added.\n")
  • 保留原内容,把新内容追加在末尾

✅ 3. 写入多行内容

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)  # 注意:每行必须带 \n

✅ 4. 写入并读取(w+

with open("output.txt", "w+", encoding="utf-8") as f:
    f.write("Write and read.\n")
    f.seek(0)  # 回到文件开头
    print(f.read())

🧠 小贴士:

  • 使用 with open(...) 会自动关闭文件,防止资源泄露。
  • 写入内容后,记得加换行符 \n,否则内容会连在一起。
  • 若文件路径不存在,可先用 os.makedirs() 创建目录。
  • 不带+读取会报错:“io.UnsupportedOperation: not readable”

三、相对路径和绝对路径

相对路径 是相对于当前运行脚本的位置,或者你设置的“工作目录”。

project/
├── main.py
└── data/
└── input.txt

绝对路径是从磁盘根目录开始的完整路径,和当前目录无关。

更可靠,但不推荐硬编码,否则跨平台和移植不方便。

你可以通过以下方法来判断一个路径是相对路径还是绝对路径


✅ 1. 使用 os.path.isabs() 判断

import os

print(os.path.isabs("/Users/alice/file.txt"))     # True(绝对路径)
print(os.path.isabs("data/input.txt"))             # False(相对路径)

✅ 2. 使用 pathlib.Path().is_absolute()

from pathlib import Path

print(Path("/home/user/data.txt").is_absolute())  # True
print(Path("docs/readme.md").is_absolute())       # False

🧠 判断逻辑(你也可以自己看出来):

📌 绝对路径的特点:

  • Unix/Linux/macOS:以 / 开头 → /home/user/data.txt
  • Windows:以 盘符:\ 开头 → C:\Users\name\file.txtD:/data/test.txt

📌 相对路径的特点:

  • 不以 /(Unix)或 盘符:(Windows)开头
  • 相对于当前工作目录os.getcwd()

✅ 示例对比

路径 类型 说明
/usr/local/bin 绝对路径 Unix 系统绝对路径
C:\Windows\Fonts 绝对路径 Windows 下的绝对路径
data/input.txt 相对路径 相对于当前运行目录
./data/input.txt 相对路径 当前目录下的相对路径
../output.txt 相对路径 上一级目录下的文件

✅ 获取绝对路径(从相对路径)

import os

rel_path = "data/input.txt"
abs_path = os.path.abspath(rel_path)
print(abs_path)

或者用 pathlib

from pathlib import Path

rel_path = Path("data/input.txt")
print(rel_path.resolve())