1 # 1. 打开文件
2
3 # 相对路径, 相对于哪一个目录下面的指定文件
4 # f = open("a.txt", "r+")
5 #
6 # # 2. 读写操作
7 # content = f.read()
8 # print(content)
9 # #
10 # f.write("88888")
11 #
12 #
13 # # 3. 关闭文件
14 # f.close()
15
16
17
18
19 # 1. 打开xx.jpg文件, 取出内容, 获取内容的前面半部分
20 # 1.1 打开文件
21 # fromFile = open("xx.jpg", "rb")
22 #
23 # # 1.2 读取文件内容
24 # fromContent = fromFile.read()
25 # print(fromContent)
26 #
27 # # 1.3 关闭文件
28 # fromFile.close()
29 #
30 #
31 # # 2. 打开另外一个文件xx2.jpg, 然后, 把取出的半部分内容, 写入到xx2.jpg文件里面去
32 # # 2.1 打开目标文件
33 # toFile = open("xx2.jpg", "wb")
34 #
35 # # 2.2 写入操作
36 # content = fromContent[0: len(fromContent) // 2]
37 # toFile.write(content)
38 #
39 #
40 # # 2.3 关闭文件
41 # toFile.close()
42
43
44
45 # f = open("a.txt", "rb")
46 #
47 # print(f.tell())
48 # f.seek(-2, 2)
49 # print(f.tell())
50 #
51 # print(f.read())
52 # print(f.tell())
53 #
54 #
55 #
56 # f.close()
57
58 # f = open("a.txt", "r")
59
60 # f.read(字节数)
61 # 字节数默认是文件内容长度
62 # 下标会自动后移e
63 # f.seek(2)
64 # content = f.read(2)
65 # print(f.tell())
66 # print(content)
67
68
69
70 # f.readline([limit])
71 # 读取一行数据
72 # limit
73 # 限制的最大字节数
74 # print("----", f.tell())
75 # content = f.readline()
76 # print(content, end="")
77 # print("----", f.tell())
78 #
79 #
80 #
81 # content = f.readline()
82 # print(content, end="")
83 #
84 #
85 # print("----", f.tell())
86 #
87 # content = f.readline()
88 # print(content, end="")
89 #
90 # print("----", f.tell())
91
92
93
94 # f.readlines()
95 # 会自动的将文件按换行符进行处理
96 # 将处理好的每一行组成一个列表返回
97
98 # content = f.readlines()
99 # print(content)
100 #
101 #
102 # f.close()
103
104
105 import collections
106
107
108 # f = open("a.txt", "r")
109
110 # print(isinstance(f, collections.Iterator))
111 #
112 # for i in f:
113 # print(i, end="")
114 #
115 # if f.readable():
116 # content = f.readlines()
117 # for i in content:
118 # print(i, end="")
119
120 # f.close()
121
122 # f = open("a.txt", "r")
123 #
124 # if f.writable():
125 # print(f.write("abc"))
126 #
127 #
128 # f.close()
129
130
131
132 f = open("a.txt", "w")
133
134
135 f.write("123")
136
137
138 f.flush() #即刻关闭,清除缓存
139
140 f.close()
![]()
1 import os
2
3 # os.rename("b.txt", "bb.txt")
4 # os.rename("first", "one")
5
6
7
8 # os.rename("one/one.txt", "two/two.txt")
9
10 # os.renames("one/one.txt", "two/two.txt") #树状修改
11
12
13
14
15
16
17
18 # os.remove("xx2.jpg")
19
20
21
22 # os.rmdir("one/one2")
23
24
25 # os.removedirs("one/one2") #递归删除
26
27
28
29
30
31
32
33 #创建目录
34 # os.mkdir("a")
35 # os.mkdir("b/c/d") #不支持创建多级目录
36
37
38 # os.mkdir("b", 0o777)
39
40 # os.chdir("a")
41 #
42 #
43 # open("dd.txt", "w") # open("目录/dd.txt", "w")
44
45
46 # 获取当前目录
47 # os.getcwd()
48
49 # print(os.getcwd())
50 # 改变默认目录
51 # os.chdir("目标目录")
52 # 获取目录内容列表
53 # os.listdir("./")
54
55
56 # print(os.listdir("a"))
57 # print(os.listdir("../"))
文件相关操作