victory的博客

长安一片月,万户捣衣声

0%

python | 文件操作

文件操作

由于我在之前上传的博客文件(markdown文件)中使用了缩进表示代码块,这中方式显示的代码块不够美观,最近发现可以使用

来表示python代码块,以这种方式表示的代码块非常美观。但是我的博客中可能有上百篇需要去修改,因此考虑使用python自动化修改,这个过程需要使用文件操作方面的知识,因此又将python文件操作相关知识又练习了一遍,然后再抽出时间去修改博客文件代码块的表示方式。

注意: 在打开文件时,当mode选择’w+’,’a+’,’ab+’,’wb+’时,虽然官方文档说明这几种模式为可读可写,但是在使用这几种模式读文件时,读出内容为空,原因见以上示例中。

示例

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# 1.打开文件、文件读写、文件关闭
"""
打开文件
f = open(filename, mode) # mode:r,w,a,rb,wb,ab,r+,w+,a+,rb+,wb+,ab+

读文件
f.readlines() # 读取整个文件的内容,返回一个文件内容列表
f.read(num) # 读取num个字节的内容,如果不写则读取文件中全部内容
f.readline() # 读取文件中的一行内容
f.readable() # 文件是否可读

写文件
f.write() # 向文件中写入一行内容
f.writelines(list) # 向文件中写入多行内容,list为要写入文件的内容列表
f.writable() # 文件是否可写

关闭文件
f.close()
"""
# 打开文件


# 测试只读模式

# 文件存在
"""
test_mode_r.txt
content:
test mode r
"""
mode = 'r' # 只读模式,从头开始读
f = open('test_mode_r.txt', mode)
print(f.readlines()) # ['test mode r']
f.close()

# 文件不存在
mode = 'r'
f = open('test_mode_r1.txt', mode) # FileNotFoundError: [Errno 2] No such file or directory: 'testt.txt'


# 测试只写模式

# 测试文件存在时只写模式
"""
test_mode_w.txt
content:
there are some texts.
"""
mode = 'w' # 只写模式,文件存在则覆盖,不存在创建新文件
f = open('test_mode_w.txt', mode)
f.writelines('this is mode r test.') # 覆盖文件原有内容
f.close()
"""
result:
this is mode r test.
"""

# 测试文件不存在时只写模式
f = open('test_mode_w1.txt', 'w')
f.write("this is mode r test.")
f.close()
"""
创建文件并写入文本

test_mode_w1.txt
content:
this is mode r test.
"""

# 测试追加模式

# 测试文件存在时追加模式
"""
test_mode_a.txt
context:
there are some texts.
"""
mode = 'a' # 追加,文件已存在向文件中追加新内容,文件不存在则创建新文件
f = open('test_mode_a.txt', mode)
f.write('\nthis is a test.') # 向文件末尾追加内容
f.close()
"""
test_mode_a.txt
context:
there are some texts.
this is a test.
"""

# 测试文件不存在时追加模式
f = open('test_mode_a1.txt', 'a') # 新建test_mode_a1.txt文件
f.write('this is a test.\n') # 向文件末尾追加内容
f.close()
"""
test_mode_a1.txt
content:
this is a test.
"""

# 测试二进制只读

# 文件存在
"""
test_mode_rb.txt
content:
this is mode rb test.
this is mode rb test.
"""
mode = 'rb' # 二进制只读模式
f = open('test_mode_rb.txt', mode)
print(f.readlines()) # [b'this is mode rb test.\r\n', b'this is mode rb test.']
f.close()

# 文件不存在
mode = 'rb' # 抛出文件不存在异常
f = open('test_mode_rb1.txt', mode) # FileNotFoundError: [Errno 2] No such file or directory: 'test_mode_rb1.txt'


# 测试二进制只写

# 文件存在
"""
test_mode_wb.txt
content:
there are some text.
"""
mode = 'wb' # 以二进制方式写入,若文件存在,则覆盖原有内容
f = open('test_mode_wb.txt', mode)
f.write('binary writing'.encode())
f.close()
"""
test_mode_wb.txt
content:
binary writing
"""

# 文件不存在
mode = 'wb'
f = open('test_mode_wb1.txt', mode) # 文件不存在时,创建新的文件,然后以二进制方式写入
f.write('this is mode wb test.'.encode())
f.close()
"""
test_mode_wb.txt
content:
this is mode wb test.
"""

# 测试二进制方式追加

# 文件存在
"""
test_mode_ab.txt
content:
there are some texts.
"""
mode = 'ab'
f = open('test_mode_ab.txt', mode) # 文件存在时,以二进制方式在文件末尾追加内容
f.write('\nthis is mode ab test.'.encode())
f.close()
"""
test_mode_ab.txt
content:
there are some texts.
this is mode ab test.
"""

# 文件不存在
mode = 'ab'
f = open('test_mode_ab1.txt', mode)
f.write('this is mode ab test.'.encode())
f.close()
"""
test_mode_ab1.txt
content:
this is mode ab test.
"""

# 测试r+

# 文件存在
"""
test_mode_r+.txt
content:
there are some texts
"""
mode = 'r+'
f = open('test_mode_r+.txt', mode)
print(f.readlines()) # 读
f.write('\nthis is mode r+ test.') # 写
f.close()
"""
test_mode_r+.txt
content:
there are some texts.
this is mode r+ test.
"""

# 文件不存在
mode = 'r+'
f = open('test_mode_r+1.txt', mode) # FileNotFoundError: [Errno 2] No such file or directory: 'test_mode_r+1.txt'


# 测试w+

# 文件存在
"""
test_mode_w+.txt
content:
there are some texts.
"""
mode = 'w+'
f = open('test_mode_w+.txt', mode)
f.write('this is mode w+ test.') # 文件中的内容变为:this is mode w+ test.
f.close()
f = open('test_mode_w+.txt', mode)
print(f.tell()) # 0
print(f.readlines()) # []
f.close()
"""
注意:
1)官方解释:w+模式打开一个文件用于文件读写
2)我们读取出来的内容为空

我们可以看到我们使用f.tell()查看指针位置,指针的位置为0,既指向文件开头,
同时,运行以w+方式打开文件的代码,打开文件发现内容为空,也既以w+方式打开文件,
会将文件中的内容清空,因此我们读不到内容。

总结:w+可以读文件(程序能够正常运行且不会抛出异常),但是读不出内容
"""

# 文件不存在
mode = 'w+'
f = open('test_mode_w+1.txt', mode)
f.write('this is mode w+ test.') # 文件内容变为:this is mode w+ test.
f.close()
f = open('test_mode_w+1.txt', mode)
print(f.readlines()) # []读取内容为空
f.close()


# 测试a+

# 文件存在
"""
test_mode_a+.txt
content:
there are some texts.
"""
mode = 'a+'
f = open('test_mode_a+.txt', mode)
f.write('\nthis is mode a+ test.')
f.close()
f = open('test_mode_a+.txt', mode)
print(f.readlines()) # [] a+模式,打开文件后,指针指向文件末尾,故也读不出内容。
f.close()
"""
test_mode_a+.txt
content:
there are some texts.
this is mode a+ test.
"""

# 文件不存在
mode = 'a+'
f = open('test_mode_a+1.txt', mode)
f.write('this is mode a+ test.')
f.close()
"""
test_mode_a+1.txt
content:
this is mode a+ test.
"""


# 测试rb+

# 文件存在
"""
test_mode_rb+.txt
content:
there are some texts.
"""
mode = 'rb+'
f = open('test_mode_rb+.txt', mode)
print(f.readlines()) # [b'there are some texts.']
f.write('\nthis is rb+ mode test.'.encode())
f.close()
"""
test_mode_rb+.txt
content:
there are some texts.
this is rb+ mode test.
"""

# 文件不存在
mode = 'rb+'
f = open('test_mode_rb+1.txt', mode) # FileNotFoundError: [Errno 2] No such file or directory: 'test_mode_rb+1.txt'

# 测试wb+

# 文件存在
"""
test_mode_wb+.txt
content:
there are some texts.
"""
mode = 'wb+'
f = open('test_mode_wb+.txt', mode)
f.write('this is wb+ mode test.'.encode()) # 文件内容变为:this is wb+ mode test.
f.close()
f = open('test_mode_wb+.txt', mode)
print(f.readlines()) # 与w+模式相同,打开文件时会清空文件内容,读不出内容
f.close()

# 文件不存在
mode = 'wb+'
f = open('test_mode_wb+1.txt', mode) # 新建文件test_mode_wb+1.txt
f.write('this is wb+ mode test.'.encode()) # 向文件中写入内容
f.close()
f = open('test_mode_wb+.txt', mode)
print(f.readlines()) # 与w+模式相同,打开文件时会清空文件内容,读不出内容
f.close()

# 测试ab+

# 文件存在
"""
test_mode_ab+.txt
content:
there are some texts.
"""
mode = 'ab+'
f = open('test_mode_ab+.txt', mode) # 打开文件
f.write('this is ab+ mode test.'.encode()) # 以二进制形式向文件末尾追加内容
f.close()
"""
test_mode_ab+.txt
content:
there are some texts.
this is ab+ mode teset.
"""
# 文件不存在
mode = 'ab+'
f = open('test_mode_ab+1.txt', mode) # 新建test_mode_ab+1.txt文件
f.write('this is ab+ mode test.'.encode()) # 以二进制形式向文件中追加内容
f.close()
"""
test_mode_ab+1.txt
content:
this is ab+ mode test.
"""


# 2.文件的定位读写

# 获取当前读写位置
f = open('current_position.txt', 'r')
string = f.read(4)
print(string)
curr_pos = f.tell() # f.tell()获取当前读写的位置
print("当前文件指针位置:", curr_pos)
f.close()

# 定位到某个位置
"""
f.seek(offset, from)

offset:偏移量

from:方向
0:文件开头
1:当前位置
2:文件末尾
"""
f = open('current_position.txt', 'rb')
string = f.read(4)
print("读取4个字节的字符串:", string)
curr_pos = f.tell()
print("当前文件指针位置:", curr_pos)
# f.seek(5, 0)
f.seek(5, 1)
"""
报错:io.UnsupportedOperation: can't do nonzero end-relative seeks

原因:没有以二进制方式打开文件,只允许从文件头开始计算相对位置,从其他位置计算相对位置会报错。
"""
print("当前文件指针位置:", f.tell())


# 3.文件的重命名、删除

# 文件重命名
import os
os.rename("old_name.txt", "new_name.txt")

# 删除文件
import os
os.remove("new_name.txt")


# 4.文件夹操作

# 创建文件夹
import os
os.mkdir("directory")

# 获取当前目录
print(os.getcwd())

# 改变默认目录
os.chdir(r"E:\my\python_project\leetcode\文件操作\directory")
print(os.getcwd())

# 获取目录列表
print(os.listdir("./"))

# # 删除文件夹
os.rmdir("directory")