学习自《python编程快速上手——让繁琐的工作自动化》

os基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os

# 返回文件路径字符串,包含正确路径分隔符
os.path.join('usr', 'bin', 'spam')

# 返回当前工作目录
os.getcwd()

# 改变当前工作路径
os.chdir()

# 创建新文件夹
os.makedirs()

# 返回参数的绝对路径
os.path.abspath(path)

#若参数为相对路径返回False,否则返回True
os.path.isabs(path)

# 返回参数start到path的相对路径,若无start,则返回当前到path的相对路径
os.paath.relpath(path, start)

# 返回目录名称
os.path.dirname(path)

# 返回基本名称
os.path.basename(path)

# 返回目录名称和基本名称
os.path.split(path)

# 正确的文件夹分割斜杠
os.path.sep

# 分割路径每个部分
path.split(os.path.sep)

# 返回path参数中文件字节数
os.path.getsize(path)

# 返回文件名字符串的列表
os.listdir()

# 检查path所值文件文件夹是否存在
os.path.exists(path)

# 检查path所指是否是一个存在的file文件
os.path.isfile(path)

# 检查path所指是否是一个存在的文件夹
os.path.isdir(path)

读写一般文件基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 打开path所指文件,返回file对象,
# 第二参数不加默认为'r'只读;为'w',覆写;为'a',添加
open(path, arg)

# 获取并返回文件内容
file.read()

# 获取文件内容,并返回包含每一行的列表
file.readlines()

# 写入或添加文件
file.write(string)

# 关闭文件
file.close()

shelve基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 利用shelve模块,可以将python程序中的变量保存到二进制的shelf文件中
import shelve

# 打开shelf文件
file = shelve.open(path)

# 修改shelf文件
file['key'] = 'value'

# 关闭shelf文件
file.close()

# 将shelf转为列表,便于使用
list(file.keys())
list(file.values())

其它

  1. 路径分隔:windows使用反斜杠\,osx和Linux使用斜杠/
  2. 大小写:windows和osx不区分大小写,Linux区分大小写。
  3. 相对路径和绝对路径,略。
  4. .表示当前文件夹..表示父文件夹