在 Python 中,可以使用内置函数 open() 创建、读取和写入文本文件。路径可分为绝对路径和相对路径。
C:/Users/username/Documents/my_folder/my_file.txt)my_folder/my_file.txt)可使用 os.getcwd() 查看当前工作目录。
import os
print("当前工作目录为:", os.getcwd())
当前工作目录为: C:\Users\Zhouq\Desktop
语法格式:
file_object = open(file_path, mode, encoding='utf-8')
常用模式说明:
| 模式 | 含义 |
|---|---|
| 'r' | 读取(默认) |
| 'w' | 写入(覆盖原内容) |
| 'x' | 独占写入(文件存在则失败) |
| 'a' | 追加 |
| 't' | 文本模式(默认) |
| 'b' | 二进制模式 |
| '+' | 读/写模式 |
file = open("test.txt", "w", encoding="utf-8")
file.write("Hello, world!\n")
file.write("This is a test file.")
file.close()
file = open("test.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()
Hello, world! This is a test file.
file = open("test.txt", "r", encoding="utf-8")
for line in file:
print(line.strip())
file.close()
Hello, world! This is a test file.
with open("test.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Hello, world! This is a test file.
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
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.