Python基础入门 Day76 文件操作基础

73次阅读
没有评论

共计 1102 个字符,预计需要花费 3 分钟才能阅读完成。

在编程过程中,文件操作是非常常见的任务。Python 提供了简洁易用的文件操作接口,可以方便地实现文件的读写与管理。

  1. 打开文件
    使用 open() 函数可以打开一个文件:
f = open("example.txt", "r")  # "r" 表示只读模式

常见模式有:

  • "r":只读模式(默认)
  • "w":写入模式(会覆盖原有内容)
  • "a":追加模式(在文件末尾追加内容)
  • "rb" / "wb":二进制读写模式
  1. 读取文件内容
f = open("example.txt", "r")
content = f.read()  # 读取整个文件
print(content)
f.close()

还可以逐行读取:

f = open("example.txt", "r")
for line in f:
    print(line.strip())
f.close()
  1. 写入文件
f = open("output.txt", "w")
f.write("Hello, Python!\n")
f.write(" 写入新的一行 \n")
f.close()

如果要在文件末尾追加内容,可以用 "a" 模式:

f = open("output.txt", "a")
f.write(" 追加的内容 \n")
f.close()
  1. 使用 with 管理文件
    为了避免忘记关闭文件,可以使用 with 语句,它会在代码块结束后自动关闭文件:
with open("example.txt", "r") as f:
    content = f.read()
    print(content)

写入文件时同样适用:

with open("output.txt", "w") as f:
    f.write(" 这是使用 with 写入的内容 ")
  1. 读取指定字节数
with open("example.txt", "r") as f:
    print(f.read(10))  # 读取前 10 个字符
  1. 读取到列表
with open("example.txt", "r") as f:
    lines = f.readlines()
    print(lines)
  1. 文件指针操作
    文件读写时有一个“指针”,可以用 seek() 移动位置,用 tell() 获取位置:
with open("example.txt", "r") as f:
    print(f.read(5))    # 读取前 5 个字符
    print(f.tell())     # 显示当前位置
    f.seek(0)           # 移动到开头
    print(f.read(5))

总结:
文件操作在 Python 中非常直观,掌握 open()read()write()with 语句的用法是后续处理数据文件的基础。

练习与思考:

  1. 创建一个 data.txt 文件,写入 5 行文本,然后逐行读取并打印。
  2. 尝试读取一个大文件,只输出前 20 个字符。
  3. 编写一个程序,将用户输入的内容不断追加到 log.txt 文件中。
正文完
 0
评论(没有评论)