Python基础-文件读写、JSON

栏目: 后端 · 前端 · 发布时间: 5年前

内容简介:r:只读,文件不存在,会报错w: 只写,会清空原有内容,文件不存在会新建a: 追加写,不会清空,文件不存在会新建
username,12345678
username2,abc12345

用户注册

#1.注册:
    #用户和密码存在文件里面
    #username,123456
    #username2,abc123
#读写文件
    #1.要从文件里面取出来所有的用户名
    #2.如果不存在就写入,存在就报用户名已注册

f = open("users.txt",'a+')
#f.seek(0)
res = f.read()
all_user_name = [] #存放所有的用户名
for r in res.split('\n'): #['username,123456','username2,abc123']
    #'username,123456'
    username = r.split(',')[0]
    all_user_name.append(username)
for i in range(3):
    username = input('username:').strip()
    pwd = input('pwd:').strip()
    cpwd = input('cpwd:').strip()
    if not(len(username) > 6 and len(username) < 20):
        print("用户名长度不合法")
    elif not (len(pwd) >=8 and len(pwd) <= 20):
        print("密码长度不合法")
    elif pwd != cpwd:
        print("两次输入的密码不一致")
    elif username in all_user_name:
        print("用户名已经注册")
    else:
        user_info = '%s,%s\n'%(username,pwd)
        f.write(user_info)
        print("注册成功")
        break
f.close()

用户登陆

# 用户从user.txt 中读取帐户和密码进行登陆
# res = open('users.txt').read()
# username = input('username:')
# pwd = input("pwd:")
# user_info = username+','+pwd
# if user_info in res:
#     print("登陆成功")
# else:
#     print("登陆失败,帐号或密码错误")
#

all_user = {}
res = open('users.txt').read()
for r in res.split('\n'): #['username,12345678','username2,abc12345']
    #'username,12345678' ['username,12345678']
    if r.strip() != '':
        username = r.split(',')[0]
        pwd = r.split(',')[1]
        all_user[username] = pwd
for i in range(3):
    username = input("username:")
    pwd = input('pwd:')
    if username in all_user:
        #if pwd == all_user.get(username):
        if pwd == all_user[username]:
            print("欢迎登录!")
        else:
            print("帐号/密码错误!")
    else:
        print("该用户未注册")

文件读写

r:只读,文件不存在,会报错

w: 只写,会清空原有内容,文件不存在会新建

a: 追加写,不会清空,文件不存在会新建

r+: 读写模式,文件不存在会报错

w+: 写读模式,文件不存在会创建,文件会被删除后重写

a+: 追加读模式,文件不存在会创建,文件只会被追加

rb、wb、ab: 以二进制方式,多用于图像,多媒体数据等

文件读

f = open('users.txt')
print(f.read()) #获取到文件里面所有的内容
print(f.read()) #再次读时会读不到内容
print(f.readlines()) #文件中所有内容,返回为list,文件中每行分别为一个元素
print(f.readline())  #一次读取一行内容

文件写

f1 = open('users.txt','a')
a=['username1,123456\n','usrname2,123456\n']

for i in a:
    f1.write(i) #每次写入一行

f1.writelines(a) #writelines()方法用于将list写入文件

文件访问次数记录练习

# 1.要从日志中访问超过200次的
# 2.每分钟都运行一次
#思路:
    # 1.读取文件内容,获取IP地址
    # 2.把每个IP地址存起来
    #['192.168.1.1','192.168.1.2','192.168.1.3']
    # 3.以字典方式存{'192.168.1.1':2,'192.168.1.3':5}
    #判断ip访问次数超过200次,如果字典的value超过200,加入黑名单

import time
point = 0 #初始的位置
while True:
    ips = {}
    f = open('access.log',encoding='utf-8')
    f.seek(point)
    for line in f: #循环读取文件里面每行数据
        ip = line.split(' ')[0] #按照空格分隔,取第一个元素ip
        if ip in ips: #判断这个IP是否存在
            ips[ip] += 1 #如存在,次数+1
        else:
            ips[ip] = 1 #不存在,IP次数为1
    point = f.tell() #记录文件指针位置
    f.close()
    for ip,count in ips.items(): #循环这个字典,判断次数大于200的
        if count >= 200:
            print("%s 加入黑名单"%(ip))
    time.sleep(60)

高效处理文件

f = open('access.log',encoding='utf-8') #f叫文件对象或文件句柄
#第一种用while循环
while True:
    line = f.readline() #一次只取一行
    if line != '':
        print(line)
    else:
        print("文件内容读完,结束")
        break

#第二种直接遍历文件
for line in f:
    print(line)

修改文件内容

#简单直接的方式
f = open(r'D:\file.txt',encoding='utf-8')
res = f.read().replace('一点','二点')
f.close()
f = open(r'D:\file.txt','w',encoding='utf-8')
f.write(res)
f.close()
#方式二
f1 = open('file.txt','w+',encoding='utf-8')
f1.seek(0)
res = f1.read().replace('一点','hello')
f1.seek(0)
f1.truncate() #清空文件里的内容
f1.write(res)
f1.close()
import os
f2 = open('file.txt',encoding='utf-8')
f3 = open('file.txt.bak','w',encoding='utf-8')
for line in f2:
    new_line = line.replace('NI','NIIIIIIII')
    f3.write(new_line)
f2.close()
f3.close()

os.remove('file.txt')
os.rename('file.txt.bak','file.txt')
import os
with open('file.txt',encoding='utf-8') as f1, open('file.txt.bak','w',encoding='utf-8') as f2: #使用with时,文件不用就会被自动关闭,可同时打开多个文件
    for line in f1:
        new_line = line.replace("二点",'一点')
        f2.write(new_line)
os.remove('file.txt')
os.replace('file.txt.bak','file.txt')

JSON处理

JSON是一种通用的数据类型,所有的语言都认识

JSON是字符串

方法如下:

  • loads() 字符串转为字典
  • dumps() 字典转为字符串
  • load() 直接传入一个含有字符串的文件对象,将字符串转为字典
  • dump() 传入字典和文件对象,将字典转为字符串

如果涉及到文件,使用load()和dump()更方便

字符串转成字典
s = '''
{
        "error_code": 0,
        "stu_info": [
                {
                        "id": 8410,
                        "name": "小黑1",
                        "sex": "男",
                        "age": 28,
                        "addr": "河南省济源市北海大道32号",
                        "grade": "天蝎座",
                        "phone": "13488709889",
                        "gold": 10401
                },
                {
                        "id": 11089,
                        "name": "小黑1",
                        "sex": "男",
                        "age": 28,
                        "addr": "河南省济源市北海大道32号",
                        "grade": "天蝎座",
                        "phone": "18612511124",
                        "gold": 100
                }
        ]
}
'''

import json
res = json.loads(s) #json串(字符串),转成字典
print(res)
print(res.keys)
print(type(res))
字典转为字符串
stus = {'xiaojun':'123456','xiaohei':'7891','xiaoliu':'111111','海龙':'111'}
res2 = json.dumps(stus, indent=4,ensure_ascii=False) #indent为缩进,中文默认使用的ascii编码,中文需要ensure_ascii=False
print(res2)
print(type(res2))
with open('stus.json','w',encoding='utf-8') as f:
    f.write(res2)
可以通过读取文件中内容,将字符串转为字典
f = open('stus.json',encoding='utf-8')
content = f.read()
user_dict = json.loads(content)
print(user_dict)
可能直接通用load(),传入文件对象将字符串转为字典
f = open('stus.json', encoding='utf-8')
user_dict = json.load(f) #load()可以直接传入一个文件对象
print(user_dict)
使用dump()传入字典和文件对象将字典转为字符串
stus = {'xiaojun':'123456','xiaohei':'7891','xiaoliu':'111111','海龙':'111'}
f = open('stus2.json','w',encoding='utf-8')
json.dump(stus, f, indent=4, ensure_ascii=False)

以上所述就是小编给大家介绍的《Python基础-文件读写、JSON》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Information

The Information

James Gleick / Vintage / 2012-3-6 / USD 16.95

James Gleick, the author of the best sellers Chaos and Genius, now brings us a work just as astonishing and masterly: a revelatory chronicle and meditation that shows how information has become th......一起来看看 《The Information》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换