python文件操作

文件操作的基本流程:

1、打开文件f_read = open("filename",mode = 'r',encoding="utf-8") 

    打开一个文件并且将文件句柄赋值给变量f_read,模式可以有多种,如:

  • r,只读模式(默认)。

  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】

  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】

  • w+,写读

  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU

  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb

  • wb

  • ab

    文件句柄解释:在文件I/O中,要从一个文件读取数据,应用程序首先要调用操作系统函数并传送文件名,并选一个到该文件的路径来打开文件。该函数取回一个顺序号,即文件句柄(file handle),该文件句柄对于打开的文件是唯一的识别依据。要从文件中读取一块数据,应用程序需要调用函数ReadFile,并将文件句柄在内存中的地址和要拷贝的字节数传送给操作系统。当完成任务后,再通过调用系统函数来关闭该文件。-----来自‘百度’

2、通过文件句柄f_read对文件进行操作

    read([5])  默认读取整个文件,加参数表示读取5个字节

    readline()   默认读取一行,再运行一次readline()则读取下一行

    readable()  判断文件是否可读,如果可读返回True,否则返回False

    readlines()  把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。

    write(str)  将str写到文件中,不会加换行符 

    writable()  判断文件是否可写,同readable

    writelines(seq)   把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

     flush()  把缓冲区的内容写入硬盘

     tell()  以文件开头为原点,返回文件操作标记的当前位置

     seek(offset[,whence])  将文件的操作标记移动到offset的位置,whence=0时,表示从头开始,=1时表示以当前位置为原点,=2时表示以文件末尾为原点。需要注意:如果文件以a或者a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾

 

3、关闭文件

    f_read.close()  即可

    PS:一般用with open("filename",'r+',encoding="utf-8") as f_read:  句式打开文件,这样等操作完成后python解释器会自动的关闭文件

 

        以下自己实现了一个对文本文件的增、删、改、查的操作,小弟不才,实现的较为曲折,还请各位指出需要优化的地方

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
import  os
 
def  operation():               #提供给用户的选择
 
     oper_dict  =  { '1' : 'find' , '2' : 'change' , '3' : 'add' , '4' : 'remove' }
 
     for  key  in  oper_dict:
 
         print (key,oper_dict[key])
 
     select  =  input ( "请选择操作:" ).strip()
 
     if  select  = =  '1'  or  select  = =  'find' :
 
         find()
 
     if  select  = =  '2'  or  select  = =  'change' :
 
         change()
 
     if  select  = =  '3'  or  select  = =  'add' :
 
         add()
 
     if  select  = =  '4'  or  select  = =  'remove' :
 
         remove()
 
def  find():
 
     out_flag  =  True           #用来跳出外层循环的标志位
 
     while  out_flag:
 
         flag  =  False
 
         =  []
 
         with  open ( 'haproxy.conf' , 'r' ,encoding = 'utf-8' ) as f_read:      #以读的方式打开文件
 
             choice  =  input ( "请输入要查找的URL:" ).strip()
 
             for  line  in  f_read:                           #遍历文件的每行并进行匹配
 
                 if  line.startswith( "backend" and  choice  in  line:
 
                     flag  =  True
 
                     continue
 
                 if  line.startswith( "backend" and  flag:
 
                     break
 
                 if  flag:
 
                     l.append(line.strip())               #将匹配到的URL之中的记录存放到l中
 
         for  in  l:                                       #输入结果
 
             print (i)
 
         =  input ( "是否继续查询?y/n" ).strip()
 
         if  = =  'y'  or  = =  'Y'  or  = =  'yes' :
 
             continue
 
         if  = =  'n'  or  = =  'N'  or  = =  'no' :
 
             out_flag  =  False
 
     # os.rename("haproxy.conf","haproxy.conf.bak")  #将原文件更名,并将修改后的文件重命名
 
     # os.rename("test","haproxy.conf")              #为了便于演示,这两行均没有运行
 
def  change():
 
     flag  =  False
 
     =  []
 
     with  open ( 'haproxy.conf' 'r' , encoding = 'utf-8' ) as f_read, open ( 'test' , 'w' ,encoding = 'utf-8' ) as f_write:
 
         choice  =  input ( "请输入要更改的记录所属的URL:" ).strip()
 
         for  line  in  f_read:                            #与查找功能一样
 
             if  line.startswith( "backend" and  choice  in  line:
 
                 flag  =  True
 
                 continue
 
             if  line.startswith( "backend" and  flag:
 
                 break
 
             if  flag:
 
                 l.append(line.strip())
 
         count  =  0
 
         for  in  l:
 
             print (count,i)
 
             count  + =  1
 
         record  =  int ( input ( "请输入要修改的记录编号:" ).strip())
 
         new_record  =  input ( "请输入新记录:" ).strip()    
                      #将输入的新记录覆盖到之前查出的列表中
 
         l[record]  =  new_record
 
     sign  =  False
 
     times  =  0
 
     with  open ( 'haproxy.conf' 'r' , encoding = 'utf-8' ) as f_read,  open ( 'test' 'w' , encoding = 'utf-8' ) as f_write:
 
         for  line  in  f_read:
 
             if  line.startswith( "backend" and  choice  in  line:
 
                 sign  =  True
 
                 f_write.write(line)
 
                 continue
 
             if  line.startswith( "backend" and  sign:
 
                 sign  =  False
 
                 f_write.write(line)
 
                 continue
 
             if  sign:
 
                 if  times <  len (l):
 
                     f_write.write( '\t\t' + l[times] + '\n' )    
                                      #将修改后的列表以行的方式写到新文件中
 
                     times  + =  1
 
                 continue
 
             else :
 
                 f_write.write(line)
 
     # os.rename("haproxy.conf","haproxy.conf.bak")
 
     # os.rename("test","haproxy.conf")
 
def  add():
 
     flag  =  False
 
     =  []
 
     with  open ( 'haproxy.conf' 'r' , encoding = 'utf-8' ) as f_read,  open ( 'test' 'w' , encoding = 'utf-8' ) as f_write:
 
         choice  =  input ( "请输入要添加的记录所属的URL:" ).strip()
 
         record  =  input ( "请输入要添加的记录:" ).strip()
 
         for  line  in  f_read:
 
             if  line.startswith( "backend" and  choice  in  line:
 
                 flag  =  True
 
                 f_write.write(line)
 
                 f_write.write( '\t\t' + record + '\n' )      
                                      #查询到需要添加的URL后,在下一行添加需要增加的行即可
 
                 continue
 
             if  line.startswith( "backend" and  flag:
 
                 flag  =  False
 
                 f_write.write(line)
 
                 continue
 
             if  flag:
 
                 f_write.write(line)
 
                 continue
 
             else :
 
                 f_write.write(line)
 
     # os.rename("haproxy.conf","haproxy.conf.bak")
 
     # os.rename("test","haproxy.conf")
 
def  remove():
 
     flag  =  False
 
     =  []
 
     with  open ( 'haproxy.conf' 'r' , encoding = 'utf-8' ) as f_read,  open ( 'test' 'w' , encoding = 'utf-8' ) as f_write:
 
         choice  =  input ( "请输入要删除的记录所属的URL:" ).strip()
 
         for  line  in  f_read:
 
             if  line.startswith( "backend" and  choice  in  line:
 
                 flag  =  True
 
                 continue
 
             if  line.startswith( "backend" and  flag:
 
                 break
 
             if  flag:
 
                 l.append(line.strip())
 
         count  =  0
 
         for  in  l:
 
             print (count, i)
 
             count  + =  1
 
         record  =  int ( input ( "请输入要删除的记录编号:" ).strip())
 
         l.pop(record)
 
     sign  =  False
 
     times  =  0
 
     with  open ( 'haproxy.conf' 'r' , encoding = 'utf-8' ) as f_read,  open ( 'test' 'w' , encoding = 'utf-8' ) as f_write:
 
         for  line  in  f_read:
 
             if  line.startswith( "backend" and  choice  in  line:
 
                 sign  =  True
 
                 f_write.write(line)                  #没有进行修改的行正常写入
 
                 continue
 
             if  line.startswith( "backend" and  sign:
 
                 sign  =  False
 
                 f_write.write(line)                  #没有进行修改的行正常写入
 
                 continue
 
             if  sign:
 
                 if  times <  len (l):
 
                     f_write.write( '\t\t'  +  l[times]  +  '\n' )    #将删除后的列表写到新文件里
 
                     times  + =  1
 
                 continue
 
             else :
 
                 f_write.write(line)
 
     # os.rename("haproxy.conf","haproxy.conf.bak")
 
     # os.rename("test","haproxy.conf")
 
operation()