Python之路:Python 基础(三)-文件操作

时间:2022-08-21 07:13:42

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件

一、打开文件

文件句柄 = file('文件路径', '模式')   # 还有一种方法open

例1、创建文件 

f = file('myfile.txt','w')        w、r、a         'rb'二进制读文件

f.write('Hello world!')

f.close( )

例2、遍历文件内容 (一行一行的读内文件内容)

a = file('myfile.txt')

for line in a.readlines():

print line

a.close( )

例3、追加

f = file('test1.txt','a')

f = write('append to the end')

f.close( )

例4、文件内容替换

for line in fileinput.input('test1.txt',inplace=1,backup='.bak'):     #表示把匹配的内容写到文件中,并先备份原文件

line = line.replace('oldtext','newtext')

print line

例5、 with open('test1.txt','r+') as f:     相当于‘例3’

Python之路:Python 基础(三)-文件操作

二、打开文件的模式有:

  • 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

Python之路:Python 基础(三)-文件操作

>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

三、with

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f: 

	...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
pass
 
四、修改配置文件
原文件:
global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 local2 info frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
需求:
1、查
输入:www.oldboy.org 获取当前backend下的所有记录
2、新建:backend字段
3、删除:backend字段
代码如下:           
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import os def fetch(backend):
backend_title = 'backend %s' % backend
record_list = []
with open('ha') as obj:
flag = False
for line in obj:
line = line.strip()
if line == backend_title:
flag = True
continue
if flag and line.startswith('backend'):
flag = False
break if flag and line:
record_list.append(line) return record_list def add(dict_info):
backend = dict_info.get('backend')
record_list = fetch(backend)
backend_title = "backend %s" % backend
current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
if not record_list:
record_list.append(backend_title)
record_list.append(current_record)
with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
for line in read_file:
write_file.write(line)
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
else:
record_list.insert(0, backend_title)
if current_record not in record_list:
record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
has_write = False
for line in read_file:
line_strip = line.strip()
if line_strip == backend_title:
flag = True
continue
if flag and line_strip.startswith('backend'):
flag = False
if not flag:
write_file.write(line)
else:
if not has_write:
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
has_write = True
os.rename('ha','ha.bak')
os.rename('ha.new','ha') def remove(dict_info):
backend = dict_info.get('backend')
record_list = fetch(backend)
backend_title = "backend %s" % backend
current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
if not record_list:
return
else:
if current_record not in record_list:
return
else:
del record_list[record_list.index(current_record)]
if len(record_list) > 0:
record_list.insert(0, backend_title)
with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
has_write = False
for line in read_file:
line_strip = line.strip()
if line_strip == backend_title:
flag = True
continue
if flag and line_strip.startswith('backend'):
flag = False
if not flag:
write_file.write(line)
else:
if not has_write:
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
has_write = True
os.rename('ha','ha.bak')
os.rename('ha.new','ha') data = "www.oldboy.org"
fetch(data)
data = '{"backend": "tettst.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 30}}'
dict_data = json.loads(data)
add(dict_data)
remove(dict_data)