9.2 txt文档的读写方法¶

在 Python 中,可以使用内置函数 open() 创建、读取和写入文本文件。路径可分为绝对路径和相对路径。

  • 绝对路径:从文件系统根目录开始(如 C:/Users/username/Documents/my_folder/my_file.txt)
  • 相对路径:相对于当前工作目录(如 my_folder/my_file.txt)

可使用 os.getcwd() 查看当前工作目录。

In [10]:
import os
print("当前工作目录为:", os.getcwd())
当前工作目录为: C:\Users\Zhouq\Desktop

9.2.3 按指定路径读写文件¶

语法格式:

file_object = open(file_path, mode, encoding='utf-8')

常用模式说明:

模式 含义
'r' 读取(默认)
'w' 写入(覆盖原内容)
'x' 独占写入(文件存在则失败)
'a' 追加
't' 文本模式(默认)
'b' 二进制模式
'+' 读/写模式

9.2.4 写入文件¶

In [5]:
file = open("test.txt", "w", encoding="utf-8")
file.write("Hello, world!\n")
file.write("This is a test file.")
file.close()

9.2.5 读取文件¶

In [6]:
file = open("test.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()
Hello, world!
This is a test file.
In [7]:
file = open("test.txt", "r", encoding="utf-8")
for line in file:
    print(line.strip())
file.close()
Hello, world!
This is a test file.

9.2.7 使用with语句¶

In [13]:
with open("test.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)
    
Hello, world!
This is a test file.

9.2.8 按行读入¶

In [ ]:
with open("example.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

9.2.9 读取指定的编码方式¶

In [ ]:
with open("example.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

使用 chardet 自动检测编码¶

In [15]:
import chardet

with open("test.txt", "rb") as f:
    data = f.read()
    result = chardet.detect(data)
    print("检测到的编码:", result)

with open("test.txt", "r", encoding=result['encoding']) as file:
    print(file.read())
检测到的编码: {'encoding': 'ascii', 'confidence': 1.0, 'language': ''}
Hello, world!
This is a test file.
In [ ]: