读操作
f = open('one','r',encoding='utf-8')
data=f.read() ##默认读取所有,可以指定读取多少个字节
print(data)
f.close()
r+ #写是追加
写操作
f = open('two','w',encoding='utf-8')
f.write('one\n') ##不存在则会创建一个新文件,存在则覆盖
f.close()
注:写入多行内容,会等到最后一次性全部写入,而不是一行写入一次。
w+ #写是追加
追加
f = open('two','a',encoding='utf-8')
f.write('three\n')
f.close()
修改
with open('file','r',encoding='utf-8') as f:
line=f.readlines()
with open('file','w',encoding='utf-8') as f1:
for i in line:
if 'zyl' in i:
i=i.replace('zyl','wq')
f1.write(i)
注:一个文件同时只能以打开一次,如果打开多次最后一次打开模式会替换之前的模式。
方法
f = open('one',encoding='utf-8')
打印一行
f.readline()
打印所有行,以列表形式展现
f.readlines()
打印文件光标位置
f.tell()
移动文件光标位置,根据字节来移动
seek(offset [,from])
##在utf-8中一个汉字占3个字节,所以文件如果是中文移动必须是3的倍数。offset,移动几位。from,从什么位置开始移动。
如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置,只有在二进制(rb,wb,ab)模式下才可以使用。
打印文件编码
f.encoding
打印文件名称
f.name
实时的写入文件
f.flush()
截断内容,仅在‘a’模式下使用,只能从开头截断,无法使用seek跳转到具体位置
f.truncate(10)
内存中可以添加数据,而硬盘中不能添加,添加会将原有位置上的数据覆盖掉。
with语句
字符编码
unicode所有字符都占两个字节
ASCLL码所有字符都占一个字节
UTF-8,英文字符都占一个字节,中文字符都占三个字节
encode(编码):按照某种规则将“文本”转换为“字节流”。 python3中表示:unicode变成bytes
decode(解码):将“字节流”按照某种规则转换成“文本”。python3中表示:bytes变成unicode,也可以变为其它类型
面向过程编程和面向函数编程
面向过程编程其实就是没有return的函数
定义一个函数
你可以定义一个由自己想要功能的函数,以下是简单的规则:
语法
Python 定义函数使用 def 关键字,一般格式如下:
def 函数名(参数列表):
函数体
优点
函数返回值
函数传参
形参与实参需要一一对应,不能多或者少
关键字传参
注:关键字参数必须放在位置参数后面
默认参数
特点:调用函数时,默认参数非必须传递
*args和**kwargs
变量作用域
递归
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
示例:
def zyl(n):
print(n)
if int(n/2) ==0:
return n
return zyl(int(n/2))
zyl(10)
输出:
10
5
2
1
特性:
高阶函数
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。
def add(x,y,f):
return f(x) + f(y)
res = add(3,-6,abs)
print(res)
注:abs函数是获取数字的绝对值
打印当前行的下一行
f = open('one','r')
b=False
count=1
for i in f:
if count ==2:
b=True
elif b:
print(i)
b=False
count+=1
打印当前行的后几行
f = open('one','r')
b=False
count=5
for i in f:
if i.find('111') >=0:
b=True
elif b and count:
print(i.strip())
count-=1
每日练习
程序1: 实现简单的shell sed替换功能
代码如下:
import os,sys
if len(sys.argv[1:]) != 3:
print('输入的参数数量不正确')
sys.exit()
source=sys.argv[1]
target=sys.argv[2]
if os.path.isfile(sys.argv[3]):
file = sys.argv[3]
else:
print('文件不存在')
sys.exit()
def openfile():
with open(file,'r') as f:
content=f.readlines()
return content
def writefile():
lines=openfile()
with open(file,'w') as f:
for line in lines:
if source in line:
line=line.replace(source,target)
f.write(line)
writefile()
程序2:修改haproxy配置文件
需求:
1、查
输入:www.oldboy.org
获取当前backend下的所有记录
2、新建
输入:{'bakend': 'www.oldboy.org','record':{'server': '100.1.7.9','weight': 20,'maxconn': 30}}
3、删除
输入:www.oldboy.org
删除当前backend下的所有记录
代码如下:
options=['search','add','delete']
def openfile():
with open('file1','r') as f:
content=f.readlines()
return content
def displayoptions():
for index,opt in enumerate(options,start=1):
print(index,opt,sep=' ')
def search(keyword):
lines=openfile()
count=2
b=False
for line in lines:
if line.startswith('backend') and line.find(keyword) >=0:
b=True
elif b and count:
print(line.strip())
count-=1
def add(arg):
with open('file1','a') as f:
f.write('\nbakend %s' % arg['bakend'])
f.write('\n\t server {} weight {} maxconn {}'.format(arg['record']['server'],arg['record']['weight'],arg['record']['maxconn']))
def delete(keyword):
lines = openfile()
count=2
b=False
with open('file1','w') as f:
for line in lines:
if keyword in line:
b=True
continue
elif b and count:
count-=1
continue
f.write(line)
def man():
while True:
displayoptions()
choice=input('请输入你的操作: ')
if choice.isdigit():
choice=int(choice)
if choice <= 3 and choice >= 1:
if choice == 1:
keyword=input('请输入关键字: ')
eval(options[choice-1])(keyword)
elif choice == 2:
keyword=input('请以字典格式写入内容: ')
if not isinstance(eval(keyword),dict):
print('数据格式不正确,请重新输入',type(eval(keyword)))
continue
eval(options[choice-1])(eval(keyword))
else:
keyword = input('请输入关键字: ')
eval(options[choice - 1])(keyword)
else:
print('输入的数字不在有效范围内')
else:
print('输入非数字')
if __name__ == '__main__':
man()
原文:https://www.cnblogs.com/SleepDragon/p/10372808.html