跳到主要内容

输入和输出

文件

文件路径

绝对路径
# linux
file_path = "~/home/30_python/test.txt"

# windows
file_path = "D:/30_python/test.txt"
# 使用转义字符
file_path = "D:\\python\\test.txt"
# 使用 r 参数, 无需使用转移字符
file_path = r"D:\python\test.txt"
相对路径
# 同目录下 test.txt 文件
file_path = "test.txt"
# 同目录下 test 文件夹中 test.txt 文件
file_path = "./test/test.txt"
# 上级目录下 test.txt 文件
file_path = "../test.txt"
# 上上级目录下 test.txt 文件
file_path = "../../test.txt"

打开并加载文件

open ()函数
  • open(file,mode,encoding=None);
    • 打开并加载文件;
    • 若文件不存在,自动生成;
    • file:文件路径;
    • mode:文件模式;
      • 'r':只读 (默认模式);
      • 'w':只写;
      • 'a':添加。
    • encoding:文件编码。
      • utf-8。
    • 返回值:file_object。
file_object.close() 方法
  • file_object.close();
    • 释放 file_object;
    • 返回值:无。
# 原始方法
# 不足, suite 语句若出现错误, file_object.close() 方法无法执行, 无法释放 file_object
file_object = open(file, mode)
file.write('hello world !'
file.close()

# 利用 try...except...finally 改进, file_object.close() 方法始终执行
file_object = open(file, mode)
try:
file.write('hello world !')
except IOError:
pass
finally:
file_object.close()

# 对上述方法的封装
# open() 返回值赋予 file_object
# 离开 with 块时, 自动执行 file_object.close() 方法
with open(file, mode) as file_object:
file.write('hello world !')

注意

换行符
  • 读文件:包括换行符;
  • 写文件。
    • 不自动添加,
    • 手动输入。
文件模式区别
  • r:只读;
  • w:只写,覆写文件内容;
  • a:只写,文件已有内容后添加。

读文件

文件模式
  • r。
file_object.read() 方法
  • file_object.read(size);
    • 读整个文件;
    • size:读取字节个数,默认为 -1 即整个文件
    • 返回值:读取字节。
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
file_object.readline() 方法
  • file_object.readline(size);
    • 读取整行;
    • size:读取字节个数,默认整行。
    • 返回值:读取字节。
with open(filename) as file_object:
# 读取第一行
line_1 = file_object.readline()
# 读取第二行
line_2 = file_object.readline()
file_object.readlines() 方法
  • file_object.readlines();
    • 读取所有行并存储至列表;
    • 返回值:列表。
with open(filename) as file_object:
lines = file_object.readlines()
for 循环实现 file_object.readlines() 方法
lines = []
with open(filename) as file_object:
for line in file_object:
lines.append(line)

写文件

文件模式
  • w;
  • a。
file_object.write() 方法
  • file_object.write(str);
    • 写文件;
    • str:写入字符串;
    • 返回值:字符串长度。
# 覆写文件
with open(filename, 'w') as file_object:
# 写入文件第一行
file_object.write("I love programming.\n")
# 写入文件第二行
file_object.write("I love creating new games.\n")

# 已有文件添加
with open(filename, 'a') as file_object:
# 已有文件后添加内容
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")

储存数据

json

引入 json 模块
import json

写 json 文件

json.dump() 方法
  • json.dump(data,file_object);
    • 写 json 文件,
    • data:存储数据;
    • file_object:储存文件。
>>> import json
>>> data = 'kxh'
>>> print(data)
kxh
>>> print(json.dumps(data))
"kxh"
>>>
json.dumps() 方法
  • json.dumps(data);
    • 转换为 json 字符串,
    • 在 data 外加 '' (不是 ""),使其变成字符串,
    • data:存储数据;
    • 返回值:str。

读 json 文件

json.load() 方法
  • json.load(file_object);
    • 读 json 文件,json.dump() 的反过程
    • file_object:读取文件;
    • 返回值:json 文件内容。
json.loads() 方法
  • json.loads(data);
    • 读 json 字符串,
    • 去除 data 外的 ''
    • data:解码数据,类型为 str;
    • 返回值:json 字符串解码内容。
>>> import json
>>> data = '"kxh"'
>>> print(data)
"kxh"
>>> print(json.loads(data))
kxh
>>>

常用 API

os 模块

os
  • os.getcwd() -> str:返回当前所在目录路径;
  • os.walk(path,topdown=True) -> tuple[list]:根据 topdown 遍历 path 路径下的所有文件/文件夹;
  • os.listdir(path) -> list[str]:返回 path 路径下的文件和文件夹名;
  • os.getcwd() -> str:返回当前所在目录路径;
  • os.getcwd() -> str:返回当前所在目录路径;
os.path

操作文件

  • os.path.exists(path) -> boolean:判断 path 对应文件/文件夹是否存在;
  • os.path.join(path,*paths) -> str:链接 path 和 paths 两个路径
os.mkdir() 方法
  • os.mkdir(path)。
    • 根据 path 创建文件夹。
    • path:文件夹路径;
    • 报错。
      • FileExistError:文件夹已存在;
      • FileNotFoundError:不存在父文件夹。
os.mkdirs() 方法
  • os.makedirs(path)。
    • 根据 path 创建一系列文件夹。
    • path:文件路径。
    • 报错。
      • FileExistError:文件夹已存在;

os.remove() 方法`

  • os.remove(path)。
    • 删除 path 对应的文件。
    • 报错。
      • FileNotFoundError:不存在文件;
      • IsADirectoryError:path 对象为文件夹。
os.rmdir() 方法
  • os.rmdir(path)。
    • 删除 path 对应的空文件夹。
    • 报错。
      • FileNotFoundError:不存在文件夹;
      • OSError:path 对象为非空文件夹。

shutil 模块

shutil
  • shutil.copyfile(src,dst) -> dst:将 src 路径的文件复制到 dst 路径下;
  • shutil.copy(src,dst) -> dst:将 src 路径的文件/文件夹复制到 dst 路径下;
  • shutil.copytree(src,dst) -> dst:将 src 路径的整个文件树复制到 dst 路径下;
  • shutil.rmtree(path) -> None:删除 path 路径下的整个文件树;