PYTHON笔记第四章之os

#数据库应用
import sqlite3                        #导入数据库
conn=sqlite3.connect('test.sqlite')   #连接数据库文件,定义句柄conn,注意文件后缀格式是sqlite
cursor=conn.cursor()                #获得句柄光标
cursor.execute('CREATE TABLE IF NOT EXISTS table01 ("num" INTEGER PRIMARY KEY NOT NULL , "tel" CHAR(9))')
#在光标处输入执行语句,创造表单如果table01不存在,属性num整型唯一关键字非空,tel电话属性是长为9个字符的串
#cursor.execute('insert into table01 values(4,"021-7777777")')
#在光标处输入执行语句,插进表单table01里面值为(num=4,tel=021-7777777)
cursor2=conn.execute('select * from table01 where num=2')   #对句柄执行查找num=2的元组返回光标给cursor2
row=cursor2.fetchone()                                      #读出光标所在行
#fetchone()函数它的返回值是单个的元组,也就是一行记录,如果没有结果,那就会返回null
#fetchall()函数,它的返回值是多个元组,即返回多个行记录,如果没有结果,返回的是()
if not row==None:                           #如果读出的元组非空
    print("{}\t{}".format(row[0],row[1]))   #输出该元组的成员
    
conn.commit()   #命令提交
conn.close()    #连接关闭
#文件IO 
print("**1**")
content='''Hello Python
haha
welcome
'''#用三引号来定义含换行的字符串
f=open('file1.txt','w') #打开文件并返回写入句柄
f.write(content)        #往文件写入字符串
f.close()               #文件关闭
f=open('file1.txt','r') #打开文件并返回读出句柄
for line in f:          #逐行读出
    print(line)         #输出该行,默认结束添加回车
f.close()

print("**2**")
f=open('file2.txt','r',encoding='UTF-8')    #打开文件并返回读出句柄
for line in f:                              #逐行读出
    print(line,end="")                      #输出该行,结束什么也不加
f.close()                                   #关闭文件
with open('file2.txt','r',encoding='UTF-8') as f:   #以utf-8编码格式打开
    doc=f.readlines()   #读出存储格式,开头有\u
    print(doc)          #输出
with open('file2.txt','r',encoding='UTF-8-sig') as f:   #以utf-8编码格式打开
    doc=f.readlines()   #读出存储格式,开头没有\u
    print(doc)          #输出
#3
print("**3**")       
f=open('file2.txt','r',encoding='UTF-8')    #打开文件获得句柄
str1=f.read(5)  #读出前五个字符
print(str1)     #输出Hell
f.close()       #关闭文件
f=open('file2.txt','r',encoding='UTF-8-sig')
str1=f.read(5)  #读出前五个字符
print(str1)     #输出Hello
f.close()       #关闭文件

'''
file1.txt与file2.txt内容是一样的
Hello Python
haha
welcome

最后输出如下:
**1**
Hello Python

haha

welcome

**2**
Hello Python
haha
welcome
['\ufeffHello Python\n', 'haha\n', 'welcome\n']
['Hello Python\n', 'haha\n', 'welcome\n']
**3**
Hell
Hello
'''

import os    #导入operation system库
dir="mydir"  #定义字符串
if(not os.path.exists(dir)): #如果当前路径下不存在以dir为名的路径
    os.mkdir(dir)   #创建文件夹
else:               #如果存在
    print("error")  #输出错误
import os    #导入operation system库
file="myfile"#定义字符串
if(os.path.exists(file)):   #如果当前路径下存在以dir为名的文件句柄
    os.remove(file)         #删除文件
else:               #如果不存在
    print("error")  #就报错
import os    #导入operation system库
dir="mydir"  #定义字符串
if os.path.exists(dir): #如果当前路径下存在以dir为名的路径句柄
    os.rmdir(dir)   #删除空目录
else:               #如果不存在
    print("error")  #就报错
import os.path                          #导入os的路径库
cur_path=os.path.dirname(__file__)      #读出当前文件的路径
print("now the dir is "+cur_path)       #输出当前路径,注意不含文件名

filename=os.path.abspath("ospath.py")   #获取以当前路径下的一个文件的句柄
if os.path.exists(filename):            #如果路径非空
    print("abspath is "+filename)       #就输出文件名(默认输出绝对路径)
    print("size is ",os.path.getsize(filename))#再输出文件大小
    basename=os.path.basename(filename) #读出文件名
    print("final name is "+basename)    #输出文件名
import os #导入库
cur_path=os.path.dirname(__file__)#now this file's path
print(cur_path)
os.system("cls")        #执行控制台指令:清屏
os.system("mkdir dir2") #执行控制台指令:创建dir2文件夹
os.system("copy ossystem.py dir2\copyfile.py")#执行控制台指令:复制当前文件到dir2下并命名为copyfile.py
file=cur_path+"\dir2\copyfile.py" #定义字符串为刚复制的文件的路径(含文件名)
os.system("notepad "+file)#执行控制台指令:用笔记本打开文件(但是我的手提NOTEPAD非DOS命令)
'''科普时间
print('{}/{}'.format('a', 'b'))#科普一下,{}就是要填的内容,以.format()表示
两种打开方式:w以写方式打开,a追加模式打开 (从 EOF 开始, 必要时创建新文件)
''' 
#帐号-密码管理系统TXT版
def menu():#提示菜单
    os.system("cls")
    print("system")
    print("----")
    print("1.input account,code")
    print("2.show account,code")
    print("3.update code")
    print("4.delete account,code")
    print("0.over")
    print("----")
    
def read_data():
    with open('password.txt','r',encoding='UTF-8-sig') as f:  #打开文件句柄
        filedata=f.read()                       #读出其数据
        if filedata != "":                      #如果读出的数据非空
            data=ast.literal_eval(filedata)     #注意literal_eval可以自动转换形式
            return data     #返回读到数据
        else:               #否则
            return dict()   #返回空
        
def disp_data():            #显示display
    print("account\tcode")
    print("---")
    for key in data:        #逐个元组读出
        print("{}\t{}".format(key,data[key]))#输出键与键值
    input("press any key to return")

def input_data():               #读入数据
    while True:                 #死循环
        name=input("accout:")   #读入名字
        if name =="":break      #名字为空可跳出
        if name in data:        #如果名字已存在
            print("error")      #报错
            continue            #继续
        password=input("code:") #输入密码
        data[name]=password     #生成映射
        with open('password.txt','w',encoding='UTF-8-sig') as f: #打开文件句柄
            f.write(str(data))  #写入文件
        print("{}OK".format(name)) #输出帐号名OK
        
def edit_data():                #编辑(修改)
    while True:                 #循环
        name=input("accout:")   #读入帐号
        if name =="":break      #空就跳出
        if not name in data:    #不存在此帐号
            print("error")      #报名
            continue            #继续
        print("old password:{} ".format(data[name]))#输出旧密码
        password=input("input please:") #读入密码
        data[name]=password             #更新映射
        with open('password.txt','w',encoding='UTF-8-sig') as f:#打开句柄
            f.write(str(data))          #继续写入
        print("{}OK".format(name))      #输出帐号名
        break

def delete_data():              #删除
    while True:                 #死循环
        name=input("accout:")   #输入帐号
        if name =="":break      #空就跳出
        if not name in data:    #帐号不存在
            print("error")      #报错
            continue            #继续
        print("are you sure to delete {}".format(name))#确定?
        yn=input("(Y/N)?")      #读出字符
        if(yn=="Y" or yn=="y"): #y
            del data[name]      #删除映射
            with open('password.txt','w',encoding='UTF-8-sig') as f:#获得句柄
                f.write(str(data))          #写入
                print("{}OK".format(name))  #输出帐号名OK
                break                       #跳出

import os,ast
data=dict()         #定义一个字典
data=read_data()    #读取数据以字典形式返回至DATA   

while True: #死循环
    menu()  #显示菜单
    choice=int(input("input please")) #输出提示并获得输入的值
    print() #换行
    if choice==1:   #1则输入
        input_data()
    elif choice==2: #2则查看
        disp_data()
    elif choice==3: #3则编辑
        edit_data()
    elif choice==4: #4则删除
        delete_data()
    else:
        break

print("over")
#帐号-密码管理系统数据库版
def menu():
    os.system("cls")
    print("management system")
    print("-----")
    print("1.add an account")
    print("2.show all accounts")
    print("3.edit your code")
    print("4.delete your code")
    print("0.over")
    print("-----")

def input_data():
    while True:
        name=input("input your account please:")
        if name=="":break
        cursor=conn.execute("select * from password where name='{}'".format(name))
        row=cursor.fetchone()
        if not row==None:
            print("error")
            continue
        password=input("input your code please:")
        conn.execute("insert into password values('{}','{}')".format(name,password))
        conn.commit()
        print("ok")      
    
def disp_data():
    cursor=conn.execute('select * from password')
    print("accout'tcode")
    print("=====")
    for row in cursor:
        print("{}\t{}".format(row[0],row[1]))
    input("press any key to return")
    
def edit_data():
    while True:
        name=input("please the account:")
        if name=="":break;
        cursor=conn.execute("select * from password where name='{}'".format(name))
        row=cursor.fetchone()
        print(row)
        if row==None:
            print("error")
            continue
        print("the old code is:{}".format(row[1]))
        password=input("please input the new code")
        conn.execute("update password set pass='{}' where name='{}'".format(password,name))
        conn.commit()
        input("press any key to return")
        break
    
def delete_data():
    while True:
        name=input("please input the account:")
        if name=="":break
        cursor=conn.execute("select * from password where name='{}'".format(name))
        row=cursor.fetchone()
        if row==None:
            print("error")
            continue
        print("sure?")
        yn=input("(Y/N)")
        if(yn=="Y" or yn=='n'):
            conn.commit("delete from password where name='{}'".format(name))
            input("over")
            break
            
            
import os,sqlite3
conn=sqlite3.connect('Sqlite01.sqlite')
while True:
    menu()
    choice=int(input("choose:"))
    print()
    if choice==1:
        input_data()
    elif choice==2:
        disp_data()
    elif choice==3:
        edit_data()
    elif choice==4:
        delete_data()
    else:
        break

conn.close()
print("over")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值