Python之路:Python 基础(三)-文件操作
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
一、打开文件
文件句柄 = 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’
二、打开文件的模式有:
- 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
>>> 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)
Python之路:Python 基础(三)-文件操作的更多相关文章
- python之路(5)文件操作(open)
目录 前言 文件的打开模式 文件句柄的方法 seek()方法介绍 前言 打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件 f = open('demo.txt','r',e ...
- Python知识点整理,基础5 - 文件操作
- Python之路Python文件操作
Python之路Python文件操作 一.文件的操作 文件句柄 = open('文件路径+文件名', '模式') 例子 f = open("test.txt","r&qu ...
- python基础篇(文件操作)
Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...
- 自学Python之路-Python基础+模块+面向对象+函数
自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python 1.1 自学Python1.1-简介 1.2 自学Python1.2-环境的 ...
- Python学习系列(五)(文件操作及其字典)
Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件 在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出 ...
- Python股票分析系列——基础股票数据操作(一).p3
该系列视频已经搬运至bilibili: 点击查看 欢迎来到Python for Finance教程系列的第3部分.在本教程中,我们将使用我们的股票数据进一步分解一些基本的数据操作和可视化.我们将要使用 ...
- Python之路Python内置函数、zip()、max()、min()
Python之路Python内置函数.zip().max().min() 一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算, ...
- Python之路Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数
Python之路Python作用域.匿名函数.函数式编程.map函数.filter函数.reduce函数 一.作用域 return 可以返回任意值例子 def test1(): print(" ...
- Python之路Python全局变量与局部变量、函数多层嵌套、函数递归
Python之路Python全局变量与局部变量.函数多层嵌套.函数递归 一.局部变量与全局变量 1.在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量.全局变量作用域是整个程序,局 ...
随机推荐
- Android Studio 代码混淆
新建一个项目,Android Studio默认关闭代码混淆开关,在build.gradle文件中,如下图所示的minifyEnabled 开关,因此如果需要混淆代码,需将false改为true,然后在 ...
- Java中static、this、super、final的用法
一. static 请先看下面这段程序: public class Hello{public static void main(String[] args){//(1)System. ...
- PHP批量下载方法
PHP批量下载方法 界面: $.get(“< ?php echo url::base(true);?>inventory/report/buildCsv”, //后台路径 {‘para ...
- xcode Simulated Metrics xib设置小问题
- C++运算符重载为非成员函数
#include<iostream> using namespace std; class Complex{ public: Complex(double r=0.0,double i=0 ...
- VS2015 启用“仅我的代码”
在调试网站的时候,如果不勾选 [启用"仅我的代码"],会跳出一大堆异常,但是异常不作处理,非常烦人: 解决办法就是在 [调试]->[选项]->[勾选 启用"仅 ...
- IS-A 和 HAS-A
IS-A关系 IS-A就是说:一个对象是另一个对象的一个分类. 下面是使用关键字extends实现继承. public class Animal{ } public class Mammal exte ...
- [Swust OJ 403]--集合删数
题目链接:http://acm.swust.edu.cn/problem/403/ Time limit(ms): 5000 Memory limit(kb): 65535 Description ...
- c++ primer plus 习题答案(2)
p221.8 #include<iostream> #include<cstdlib> #include<cstring> using namespace std; ...
- JAVA_用_JCO连接_SAP,实现调用SAP_的_RFC_函数(整理)(附一篇看起来比较全面的说明)(JCO报错信息)
// 获取RFC返回的字段值 11 JCoParameterList exportParam = function.getExportParameterList(); 12 String exPara ...