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.在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量.全局变量作用域是整个程序,局 ...
随机推荐
- URAL 1297 Palindrome(后缀数组+ST表)
[题目链接] http://acm.timus.ru/problem.aspx?num=1297 [题目大意] 求最长回文子串,并输出这个串. [题解] 我们将原串倒置得到一个新的串,加一个拼接符将新 ...
- iOS 按钮倒计时功能
iOS 按钮倒计时功能, 建议把按钮换成label,这样会避免读秒时闪烁 __block ; __block UIButton *verifybutton = _GetverificationBtn; ...
- 如何使用ssh-keygen生成key
ssh-keygen - 生成.管理和转换认证密钥 通常使用:[b]ssh-keygen -i -f 公密匙名>> authorized_keys[/b] 语法详细介绍 [code]ssh ...
- XMLHttpRequest对象的使用
1.首先要创建XMLHttpRequest对象,这个对象是前台与后台进行异步的重要对象,现在的浏览器有很多种,创建 XMLHttpRequest 的方法也不相同,所以为了兼容各种浏览器,在创建XMLH ...
- SSIS: 使用Lookup 和 Cache transformation 进行数据匹配简单介绍
本文将讲解Cache transformation的使用方式,并且用Lookup transformation进行匹配. 背景 如下图,我们的产品目标表中有些有尺寸信息有些没有.我们需要用Cache组 ...
- Objective-c 数组对象
首先我们必须知道数组的概念:数组是有序的对象集合,一般情况下,一个数组的对象都是相同类型的.数组当中也存在可变数组和不可变数组. 1. 不可变数组 (NSArray) 可变数组 NSMutable 是 ...
- 为什么C#动态调用Java的cxf多了bool型参数
最近的一个项目需要C#调用Java的cxf发布的接口,接口参数文档只给我的是两个long型,但是通过我动态加载发现,参数是四个. 比如接口文档给的接口是 TestFunc(long, long); 而 ...
- Java如何实现对Mysql数据库的行锁
场景如下: 用户账户有余额,当发生交易时,需要实时更新余额.这里如果发生并发问题,那么会造成用户余额和实际交易的不一致,这对公司和客户来说都是很危险的. 那么如何避免: 网上查了下,有 ...
- LeetCode Backpack
Given n items with size Ai, an integer m denotes the size of a backpack. How full you can fill this ...
- Eclipse4.3正式版已发布
Eclipse4.3正式版已发布,传送门http://www.eclipse.org/downloads/