文件操作分为 读 写 修改
示例:
f =open(file='db.txt',mode='r',encoding='utf-8') r 只读 r+ 读写 w+ 写读 w 写 rb 以二进制方式读取 a 把内容追加到文件尾部
data=f.read()
f.close()
循环文件
f = open(file='db.txt','r',encoding="utf-8")
for line in f :
print (line)
f.close()
写文件
f = open(file='db.txt','w',encoding="utf-8")
f.write('aslkfladfasdf')
f.close()
占硬盘方式的文件修改代码示例
模拟登陆
import os
f = oopen(f_name,'r',encoding='utf-8')
f_new=open(f_new_name,'w',encoding='utf-8')
for line in f:
if old_str in line:
new_line = line.replace(old_str,new_str)
else:
new_line = line
f_new.write(new_line)
f.close()
f_new.close()
os.rename(f_new_name,f_name)
while True:
name=input('请输入用户名>>: ')
with open ('lock.txt','r',encoding='utf-8') as read_f:
f=read_f.read()
if name in f:
print('次用户已锁定‘)
break
psw=input('请输入密码>>: ')
with open ('user.txt','r',encoding='utf-8') as read_f:
for line in read_f:
l=line.strip().split(',')
if name==l[0] and psw==l[1]:
print(‘登陆成功’’)
break
else:
print('请重新输入')
count+=1
if count=3 :
with open ('lock.txt','w',encoding='utf-8') as write_f:
write_f.write(name)
print('用户已锁定')
break
全局替换
import sys
import os
count=0 if len(sys.argv) != 3: print('usage: cp source_file target_file') sys.exit()
old_str,new_str=sys.argv[1],sys.argv[2]
with open(f_new_name,'rb') as f,open(f_new_name,'wb') as f_new:
for line in f:
if old_str in line:
new_line=line.replace(old_str,new_str)
count+=1
else:
new)line=line
f_new.write(new_line)
os.rename(f_new_name,f_name)
print('count')