设为首页 加入收藏

TOP

python 文件操作
2017-09-30 17:07:55 】 浏览:8463
Tags:python 文件 操作

打开文件的几种模式

open('path') #默认只读打开
open('path','r+') #读写模式打开。如果有内容,就会从头覆盖相应字符串的内容
open('path','w')#写入,覆盖文件,重新写入。没有文件就自己创建
open('path','w+ ')#读写,作用同上
open('path','a')# 写入,在文件末尾追加内容,文件不存在就创建
open('path','a'+)#读写,同上。 最常用
open('path','b') #打开二进制文件
open('path','U')#支持所有的换行符号
实战:登陆注册
 
#!/usr/bin/env python
#coding:utf-8
f=open('user.txt','a+')
#单行写入
#f.write("wd:1234")
#多行写入
#names=["pc:123\n","panda:123\n"]
#f.writelines(names)
#交互式注册
while True:
        name=raw_input('请输入用户姓名:').strip()
        password=raw_input('请输入您的密码:').strip()
        repass=raw_input('请再次输入密码:').strip()
        if len(name)==0:
                print "用户名不能为空,请重新输入!!"
                continue;
        if len(password)==0 or password !=repass:
                print "密码输入有误"
                continue;
        else:
                print "恭喜你,注册成功"
                break;
f.write("%s:%s" %(name,password))
f.close()

 

#!/usr/bin/env python
#coding:utf-8
fo=open("user.txt")
'''
num=1
while True:
        line=fo.readline()
#       print repr(line)
        print "%s-->%s" %(num,line.rstrip("\n"))
        num+=1
        if len(line)==0:
                break
'''
#从文件中读取所有字符,并存为字典
dict1={}
content=fo.readlines()   #讲文件结果保存为列表
fo.close()
#print content
for user in content:
        name=user.rstrip("\n").split(":")[0]
#       print name
        dict1[name]=user.rstrip("\n").split(":")[1]
#print dict1

#判断用户的账号密码。都ok提示登陆成功。否则失败
count=0
while True:
        count+=1
        if count >3:
                print "对不起,您输入的错误次数过多,账户已锁定。请联系管理员"
                break
        name=raw_input('请输入用户姓名:').strip()
        if name not in dict1:
                print "用户名不存在,请重新输入!!"
                continue;
        password=raw_input('请输入您的密码:').strip()
        if password !=dict1[name]:
                print "密码输入有误"
                continue;
        else:
                print "恭喜你,登陆成功"
                break;

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python-Day1 Python基础学习 下一篇learn-python3

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目