python--文件读写--函数

知识点一、文件读写内容

 

1、当文件当前没有写文件模式,默认为r,当文件以r的形式打开不存在的文件会报错
f = open('a.txt')
f = open('a.txt','r',encoding = 'utf-8')

文件内容:
yangmingyue
xiaohong
xiaomgg 23434
dakggak

(1)read
f = open('a.txt','r',encoding = 'utf-8')#当前没有写文件模式,默认为r
print('read',f.read())#读出文件所有内容,文件内容为字符串

(2)readlines
f = open('a.txt','r',encoding = 'utf-8')#当前没有写文件模式,默认为r
print('readlines',f.readlines())#读出文件所有内容,把文件每一行内容放在list中

(3)readline
f = open('a.txt','r',encoding = 'utf-8')#当前没有写文件模式,默认为r
print('readline',f.readline())#一次只读一行

 

 

 (4)文件指针:控制文件读到的位置

f = open('a.txt','r',encoding = 'utf-8')#当前没有写文件模式,默认为r
print('readlines',f.readlines())#读出文件所有内容,把文件每一行内容放在list中
print('readline',f.readline())#一次只读一行

f = open('a.txt','r',encoding = 'utf-8')
print('readlines',f.readlines())
print('read',f.read())

f = open('a.txt','r',encoding = 'utf-8')#当前没有写文件模式,默认为r
print('readline',f.readline())#一次只读一行
print('readlines',f.readlines())#读出文件所有内容,把文件每一行内容放在list中

2、当文件以w的模式写入文件,能写不能读,写之前会清空文件
(1)write 写入内容是字符串,就用write,
f = open('a.txt','w')
f.write('asdeeff\n')#只能写字符串
f.close()


 (2)writelines  写入list时用

f = open('a.txt','w')
f.writelines('6747888')#可以写list,自动循环list每个元素,将元素都写入文件,也可以写入集合,只能能循环的数据类型都可以写
f.close()
stus = ['xiaohong','xiaobei','xiaolan']
f = open('a.txt','w')
f.writelines(stus)#可以写list,自动循环list每个元素,将元素都写入文件
f.close()

set = {'xiaohong','xiaohei','xuangg'}
f = open('a.txt','w')
f.writelines(set)#可以写list,自动循环list每个元素,将元素都写入文件
f.close()


3、当文件以a 的模式打开不存在的文件,会追加生成新的文件,不会报错
f = open('a.txt','a',encodinga = 'utf-8')

4、r+ 能读能写,打开不存在文件报错
f = open('a.txt','r+',encoding = 'utf-8')
print(f.read())
f.write('r+模式222333')
f.close()

f = open('a.txt','r+',encoding = 'utf-8')
#print(f.read())
f.write('r+模式4444')
f.close()

 

 注意:

读与不读会影响写的位置,因为文件指针导致的
5、w+  能读能写,但是会清空之前的文件,
f = open('a.txt','w+',encoding = 'utf-8')
print(f.read())
f.write('r+模式4444')
f.close()

f = open('a.txt','w+',encoding = 'utf-8')
f.write('r+模式4444')
print(f.read())
f.close()

注意:写完之后读不到东西,想要想要读到内容,移动文件指针,f.seek(0)

6、a+ 能读能写不会清空之前的文件

f = open('a.txt','a+',encoding = 'utf-8')
print(f.read())
f.write('r+模式4444')
f.close()d

 

注意:读不到东西,文件指针导致,想要读到内容,移动文件指针,f.seek(0)

f = open('a.txt','a+',encoding = 'utf-8')
f.seek(0)
print(f.read())
f.write('r+模式4444')
f.close()

总结:

 高效读文件:打开文件,直接循环文件对象

f = open('a.txt',encoding='utf-8')

for line in f:
print('每一行的内容:',line)

列子:

#1、监控服务器日志,找出每分钟访问超过100次的ip地址
#分析:
#1、当前时间去读上一分钟的数据,死循环 while True 实现,读取文件,获取到文件里面的所有ip地址
#2、把ip地址存起来,用字典存,key是ip地址,value是次数
#3、循环字典,判断value大于100的

import time
point = 0
while True:
ips = {} # 存放所有的ip地址以及它出现的次数
f = open('access.log')#默认r 的模式,读出所有的文件内容
f.seek(point)#文件指针到文件头
for line in f:
if line.strip():#判断不为空行的时候
ip = line.split()[0]
if ip not in ips:
ips[ip] = 1
else:
ips[ip] = ips[ip]+1
point = f.tell() #当前文件指针的位置
for ip in ips:
if ips.get(ip) >= 100:
print('超过100次的ip是:%s'%ip)
time.sleep(60)

知识点二、文件修改
#方式一:
#1、先读文件,替换,将替换的文件写入文件
f = open('a.txt','a+',encoding='utf=8')
result = f.read()
new_result = result.replace('abc','ABC')
f.seek(0)
f.truncate()#清空文件内容
f.write(new_result)
f.close()

#方式二:
#一次读一行,一行一行修改

# import os
# f1 = open('test.txt',encoding="utf-8")
# f2 = open('a2.txt','w',encoding='utf-8')
# for line in f1:
# new_line = line.replace('-','1')
# f2.write(new_line)
# f1.close()
# f2.close()
# os.remove('test.txt')
# os.rename('a2.txt','test.txt')
 
 
#方法三
###使用with 不用自己关闭文件,
import os
with open('a1.txt',encoding='utf-8') as f1,open('a2.txt','w',encoding='utf-8') as f2:
for line in f1:
new_line = line.replace('-', '1')
f2.write(new_line)

os.remove('a1.txt')
os.rename('a2.txt', 'a1.txt')

程序明明运行完,文件中没有内容,原因是不同的区域运行速度不一致,处理方式:
with open ('a.txt','w')as fw:
fw.write('123')
fw.flush()#处理文件运行后没有内容
知识点三、非空即真,非0即真,判断的时候使用给,简化代码
s = ''#字符串
l = []#数组
d = {}#字典
s1 = set()#集合

username = input('user').strip()
if username:#表示内容不为空
print('欢迎登录')
else:
print('输入内容不能为空')

if not username:#表示没有内容,内容为空

知识点四、json 文件
json串就是字符串
d =  {"name":"abc"}
import json
import pprint
json_str = json.dumps(d) #就是把字典/list转成字符串(json)
pprint.pprint(json_str)

 

 效果:把字典转成字符串,用pprint,效果更明显

json_str2 = ' {"xiaohei":"123456","age":18}  '
dic = json.loads(json_str2) #把字符串(json)转成 字典
pprint.pprint(dic)
 
 
d = {"xiaohong":"123456","age":18}
with open('users.json','w',encoding='utf-8') as f:
json_d = json.dumps(d)#把字典转成字符串
f.write(json_d)
 
 
with open('users','r',encoding='utf-8') as f:
result = f.read()
a = json.loads(result)#把字符串转成字典
pprint.pprint(a)
 
 
d =  {
"id": 314,
"name": "矿泉水",
"sex": "男",
"age": 18,
"addr": "北京市昌平区",
"grade": "摩羯座",
"phone": "18317155663",
"gold": 40
}
with open('user','w',encoding = 'utf-8') as f:
json_b = json.dumps(d,ensure_ascii=False,indent=4)#ensure_ascii=False读出中文,indent=4缩进格式化
f.write(json_b)
d =  {
"id": 314,
"name": "矿泉水",
"sex": "男",
"age": 18,
"addr": "北京市昌平区",
"grade": "摩羯座",
"phone": "18317155663",
"gold": 40
}
with open('user.json','w',encoding = 'utf-8') as f:#打开json 文件后,写入格式有颜色区分
json_b = json.dumps(d,ensure_ascii=False,indent=4)#ensure_ascii=False读出中文,indent=4缩进格式化,4表示4个缩进
f.write(json_b)
import json
import pprint
d = {
"id": 314,
"name": "矿泉水",
"sex": "男",
"age": 18,
"addr": "北京市昌平区",
"grade": "摩羯座",
"phone": "18317155663",
"gold": 40
}
f = open('users','w',encoding= 'utf-8')
json.dump(d,f,ensure_ascii=False,indent = 4)

f = open('users','r',encoding= 'utf-8')
dic = json.load(f)
print(dic)

 

 知识点五、函数

#函数就是把一段代码封装起来,函数的作用就是简化代码

#告诉文件名和内容
def write_file(file_name,content):
  f = open(file_name,'w')
  f.write(content)
  f.close()

#函数里面定义的变量都是局部变量,只在函数里面可以用,出了函数就不能用了
def read_file(file_name):
  with open(file_name,encoding='utf-8') as fr:
  result = fr.read()
  return result   #函数返回值

content = read_file('users')#函数调用
# print(content)

#1、函数不写返回值的情况下返回的是空
#2、返回多个值的时候,返回的是什么
#函数里面遇到return函数立即结束运行

函数例子:
#判断是否是浮点数的函数方法  1.33,-4.5 正数负数都是浮点数
#1、必须只有一个小数点
#2、小数点的左边必须是整数,小数点的右边必须是正整数
def is_float1(s):
s = str(s) #.1
if s.count('.')==1:#小数点数量为1
left,right = s.split('.') #['-','1']左侧和右侧用小数点分割
if left.isdigit() and right.isdigit():#左右都是正整数
return True#表示正浮点数
elif left[0] == '-' and left[1:].isdigit() and right.isdigit():#左边的第一个元素是-,左边的第一个元素后和右边的元素都是正整数
return True#表示是负的浮点数
else:
return False#不是浮点数
else:
return False#不是浮点数
print(is_float1('-.1')) # 函数调用
print(is_float1('-1.1')) # 函数调用
print(is_float1('1.1')) # 函数调用
print(is_float1('s.1')) # 函数调用
print(is_float1('-s.1')) # 函数调用
简化后的代码
def is_float1(s):
s = str(s) #.1
if s.count('.')==1:#小数点数量为1
left,right = s.split('.') #['-','1']左侧和右侧用小数点分割
if left.isdigit() and right.isdigit():#左右都是正整数
return True#表示正浮点数
elif left[0] == '-' and left[1:].isdigit() and right.isdigit():#左边的第一个元素是-,左边的第一个元素后和右边的元素都是正整数
return True#表示是负的浮点数

return False#不是浮点数
简化的原因是只有不符合浮点数规则,都是返回False
print(is_float1(.1))会报错
def is_float1(s):
s = str(s) #.1
if s.count('.')==1:
left,right = s.split('.') #['-','1']
if left.isdigit() and right.isdigit():#正小数
return True
elif left.startswith('-') and left.count('-')==1 and right.isdigit():
#先判断负号开头,只有一个负号,小数点右边是整数
lleft = left.split('-')[1] #如果有负号的话,按照负号分隔,取负号后面的数字
if lleft.isdigit():#
return True
return False
print(is_float1(.1))
s='1.1'
def is_float(s):
s = str(s)
if s.count('.') == 1: # 判断小数点个数
left,right = s.split('.') # 按照小数点进行分割
if left.startswith('-') and left.count('-') == 1 and right.isdigit():
lleft = left.split('-')[1] # 按照-分割,然后取负号后面的数字
if lleft.isdigit():
return True
elif left.isdigit() and right.isdigit():# 判断是否为正小数
return True
return False
print(is_float(s))
def hhh(name): #默认值参数
print(name)
#默认值函数的参数不是必传的,
def op_file(file_name,content=None):#(必填参数,默认值参数)
if content:
f = open(file_name,'w',encoding='utf-8')
f.write(content)
else:
f = open(file_name,encoding='utf-8')
return f.read()
 
 
def abc(name,age,phone,addr,money):#
print(name)
print(age)
print(phone)
print(addr)
print(money)
abc('xiaohei',18,110,'beijing',9000)#按照位置顺序传
abc(age=18,addr='beijing',money=500,phone=111,name='111')#指定参数
abc('xiaobai',addr='123',phone=1111,money=11111,age=13)#顺序,指定参数
abc(age=13,'xiaohei')#指定参数,按照位置这种传参方式是不对滴
全局变量:公共的变量
file_name = 'users.json' #全局变量
def func():
file_name = 'abc.json'
print(file_name)
func()

print(file_name)
修改全局变量的方法
file_name = 'users.json' #全局变量
def func():
global file_name#声明修改的全局变量
file_name = 'abc.json'
print(file_name)
func()
print(file_name)
 

 

 例子:

money = 500
def test(consume):
return money - consume

def test1(money):
return test(money) + money

#常量:不会变的变量,常用大写字母定义
PI = 3.14

 

 

转载于:https://www.cnblogs.com/luoxinmoli/p/11572508.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值