1. 程式人生 > >python文件的操作

python文件的操作

most 沒有 rac == 插入 打開文件 dir pychar buffer

首先看看在pycharm輸入文件句柄,怎樣顯示他的定義

f = open(‘student_msg‘, encoding=‘utf-8‘, mode=‘a+‘) # 打開一個文件,賦值給f

print(type(f), f) # f文件句柄是屬於一個類叫<class ‘_io.TextIOWrapper‘>,也是可叠代對象。(io ---> input and out)

print(dir(f)) # 打印這個類的所有屬性和方法

>>
[‘_CHUNK_SIZE‘, ‘class‘, ‘del‘, ‘delattr‘, ‘dict‘, ‘dir‘, ‘doc

‘, ‘enter‘, ‘eq‘, ‘exit‘, ‘format‘, ‘ge‘, ‘getattribute‘, ‘getstate‘, ‘gt‘, ‘hash‘, ‘init‘, ‘init_subclass‘, ‘iter‘, ‘le‘, ‘lt‘, ‘ne‘, ‘new‘, ‘next‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘_checkClosed‘, ‘_checkReadable‘, ‘_checkSeekable‘, ‘_checkWritable‘, ‘_finalizing‘, ‘buffer‘, ‘close‘, ‘closed‘, ‘detach‘, ‘encoding‘, ‘errors‘, ‘fileno‘, ‘flush‘, ‘isatty‘, ‘line_buffering‘, ‘mode‘, ‘name‘, ‘newlines‘, ‘read‘, ‘readable‘, ‘readline‘, ‘readlines‘, ‘reconfigure‘, ‘seek‘, ‘seekable‘, ‘tell‘, ‘truncate‘, ‘writable‘, ‘write‘, ‘write_through‘, ‘writelines‘]

print(f.dict) # f 這個實例化對象中的屬性 {‘mode‘: ‘a+‘}

源碼對其的解釋定義
‘‘‘
========= ===============================================================
Character Meaning


‘r‘       open for reading (default)  默認只讀
‘w‘       open for writing, truncating the file first  首先把文件截斷(全刪了)
‘x‘       create a new file and open it for writing
‘a‘       open for writing, appending to the end of the file if it exists  追加模式
‘b‘       binary mode  二進制模式,打開圖片或者非文本格式時
‘t‘       text mode (default)  默認讀取文本
‘+‘       open a disk file for updating (reading and writing)  可讀可寫
========= ===============================================================

‘‘‘
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
文件的操作使用的頻率還是很高,這幾種方法很容易弄混,為了避免以後出現偏差,現在我把幾種常用的方法整理透。
一,.readline() 和 .readlines() 目的是瀏覽,查找文件中的內容用什麽模式。先看用六種方式執行的結果。
在register文件中有以下內容,看下分別執行這六種方式返回的結果
”’
這些是文件中的內容
dumingjun
mickle|male
”’

mode=‘r‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘r‘) as f:
print(f.readline())
print(f.readlines())

>>運行結果:(文件中內容無變化)

‘‘‘
這些是文件中的內容

[‘dumingjun\n‘, ‘mickle|male‘]
‘‘‘

mode=‘r+‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘r+‘) as f:
print(f.readline())
print(f.readlines())

>>運行結果:(文件中內容無變化)

‘‘‘
這些是文件中的內容 # 先讀了一行

[‘dumingjun\n‘, ‘mickle|male‘] # 然後往下執行,把每行作為一個字符串放入列表這個容器中,換行符為\n
‘‘‘

mode=‘w‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘w‘) as f:
print(f.readline())
print(f.readlines())

運行結果:(文件中已經沒有內容了)

‘‘‘
Traceback (most recent call last):
print(f.readline())
io.UnsupportedOperation: not readable # 報錯原因:’w‘模式是無法讀的,只要看到’w‘,先把文件全清空
‘‘‘

mode=‘w+‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘w+‘) as f:
print(f.readline())
print(f.readlines())

運行結果:(文件內容已經為空)

‘‘‘

先清空,然後接下來執行了f.readline() 由於為空,所以返回了空的字符

[] # 接下來執行f.readlines(), 返回一個空列表
‘‘‘

mode=‘a‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘a‘) as f:
print(f.readline())
print(f.readlines())

運行結果:(文件內容不變)

‘‘‘
Traceback (most recent call last):
print(f.readline())
io.UnsupportedOperation: not readable # 報錯原因,’a‘模式只能add,增加,不可讀,因為’a‘模式進去時光標自動放在文件的末尾。
‘‘‘

mode=‘a+‘

with open(‘register‘, encoding=‘utf-8‘, mode=‘a+‘) as f:
print(f.readline())
print(f.readlines())

運行結果:(文件內容不變)

‘‘‘

因為光標是放在最後,所以讀取的內容為空

[] # 同理redlines()返回的是一個空列表。
‘‘‘
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
以上代碼的內容顯示在圖片上:
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
總結
這裏寫圖片描述
閱讀,查找相關內容,只能用‘r’或 ‘r+’模式

二 現在要新建一個文件,並且添加內容,先看看五種方法運行的結果

‘‘‘
創建名為‘msg‘的文件,並寫入內容以下內容:
’Duminjun is swimming\n今晚吃雞‘
‘‘‘

r模式就不用試了,r只能讀,試試r+模式

with open(‘msg9‘, encoding=‘utf-8‘, mode=‘r‘) as f:

f.write(‘Duminjun is swimming\n今晚吃雞‘)

運行結果:

‘‘‘
Traceback (most recent call last):
with open(‘msg‘, encoding=‘utf-8‘, mode=‘r+‘) as f:
FileNotFoundError: [Errno 2] No such file or directory: ‘msg‘ # 沒有名為‘msg’的文件,證明r+模式不可添加文件
‘‘‘

a 模式

with open(‘msg‘, encoding=‘utf-8‘, mode=‘a‘) as f:

f.write(‘Duminjun is swimming\n今晚吃雞‘)

#

運行結果(已經在本目錄添加了‘msg’的文件,並且打開文件顯示了以下內容:

‘‘‘
Duminjun is swimming # a 模式可以創建文件並寫入
今晚吃雞
‘‘‘

a+模式

with open(‘msg‘, encoding=‘utf-8‘, mode=‘a+‘) as f:

f.write(‘Duminjun is swimming\n今晚吃雞‘)

運行結果:和以上a運行結果一樣

w模式

with open(‘msg‘, encoding=‘utf-8‘, mode=‘w‘) as f:

f.write(‘Duminjun is swimming\n今晚吃雞‘)

結果:和a模式一樣

w+ 模式

with open(‘msg4‘, encoding=‘utf-8‘, mode=‘w+‘) as f:

f.write(‘Duminjun is swimming\n今晚吃雞‘)

運行結果:和a模式行的結果一樣

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
圖示:
這裏寫圖片描述

三 如果有名為’msg‘的文件裏面有’Duminjun is swimming\n今晚吃雞‘這些內容,現在要增加以下內容
’\nLaura is a playing tennis,What are you dong?’ 試試這幾種方法的效果

r

with open(‘msg‘, encoding=‘utf-8‘, mode=‘r‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果:

‘‘‘
Traceback (most recent call last):
f.write(‘\nLaura is a playing tennis,What are you dong?‘)
io.UnsupportedOperation: not writable # f這個實例化對象中沒有可讀這一屬性
‘‘‘

r +

with open(‘msg‘, encoding=‘utf-8‘, mode=‘r+‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果:(沒有報錯,文件內容如下:)

‘‘‘

Laura is a playing tennis,What are you dong?s swimming
今晚吃雞 # 添加的內容已經插入到了最前面,r+模式可以寫入文件,但是進入文件句柄時光標在最前面
‘‘‘

如果想要r+模式增加內容到文末,可以先讀完全部內容,光標就到了最後,然後在把內容寫入文件

with open(‘msg‘, encoding=‘utf-8‘, mode=‘r+‘) as f:

f.readlines()

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果(文件內容如下):

‘‘‘
Duminjun is swimming
今晚吃雞
Laura is a playing tennis,What are you dong?
‘‘‘

w

with open(‘msg‘, encoding=‘utf-8‘, mode=‘w‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果,文件中顯示以下內容:

‘‘‘

Laura is a playing tennis,What are you dong? # 原文件內容全部清空,寫入了新增加的內容
‘‘‘

w+

with open(‘msg‘, encoding=‘utf-8‘, mode=‘w+‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果:和w運行結果一樣

a

with open(‘msg‘, encoding=‘utf-8‘, mode=‘a‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

#

運行結果,文件內容如下

‘‘‘
Duminjun is swimming
今晚吃雞
Laura is a playing tennis,What are you dong? # 已經成功到文末
‘‘‘

a+

with open(‘msg‘, encoding=‘utf-8‘, mode=‘a+‘) as f:

f.write(‘\nLaura is a playing tennis,What are you dong?‘)

運行結果:和a模式結果一樣

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
圖示
這裏寫圖片描述
這裏寫圖片描述

四,例題:寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個文件的批量修改操作

def modify_update():
file_name = input(‘please input the file name: ‘).strip()
modify_content = input(‘please input the content to modified: ‘)
new_content = input(‘please input new content you want to replace: ‘)
with open(‘{}‘.format(file_name), encoding=‘utf-8‘, mode=‘r+‘) as f, \
open(‘msk5‘, encoding=‘utf-8‘, mode=‘w+‘) as f1: # 打開兩個文件句柄,一個讀原文檔,一個寫入修改後的內容
for i in f:
f1.write(i.replace(‘{}‘.format(modify_content), ‘{}‘.format(new_content)))

邊循環原文件每一行,邊添加新的一行到另外一個文件,如果replace沒有找到舊詞,字符串不會做任何修改,所以不用if...else語句

‘‘‘
w,w+在一個句柄裏操作不會每次都清空,只有重新以w,w+模式打開一個句柄並且使用f.write()才會清空,就是說兩個句柄是沒有

python文件的操作