4道Python文件 *** 作和函数练习题

4道Python文件 *** 作和函数练习题,第1张

概述一.利用b模式,编写一个cp工具,要求如下:既可以拷贝文本又可以拷贝视频,图片等文件用户一旦参数错误,打印命令的正确使用方法,如usage:cpsource_filetarget_file提示:可以用importsys,然后用sys.argv获取脚本后面跟的参数#Python学习交流群:531509025#cp工具importsysif

一.利用b模式,编写一个cp工具,要求如下:

既可以拷贝文本又可以拷贝视频,图片等文件

用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file

提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数

#Python学习交流群:531509025# cp工具import sysif len(sys.argv) != 3:    print("usage: cp source_file target_file")    sys.exit()else:    source_file, target_file = sys.argv[1], sys.argv[2]    with open(source_file,"rb") as read_f,open(target_file,"wb") as write_f:        for line in read_f:            write_f.write(line)

二.Python实现 tail -f 功能

#tail -f工具import sys,timeif len(sys.argv) != 2:    print("usage: tail file_name")    sys.exit()else:    file_name = sys.argv[1]    with open(file_name,'rb') as f:        f.seek(0,2) # 每次都从文件末尾开始读        while True:            line = f.readline()            if line:                print(line.decode('utf-8'),end='') # 读取的每一行都去掉行尾的换行符            time.sleep(1)

有待优化,每次打开应该显示最后10行。

三.文件的修改

文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)
import os with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:    data=read_f.read() #全部读入内存,如果文件很大,会很卡    data=data.replace('alex','SB') #在内存中完成修改     write_f.write(data) #一次性写入新文件 os.remove('a.txt')os.rename('.a.txt.swap','a.txt')
方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件
import os with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:    for line in read_f:        line=line.replace('alex','SB')        write_f.write(line) os.remove('a.txt')os.rename('.a.txt.swap','a.txt') 

三.全局替换程序:

写一个脚本,允许用户按以下方式执行时,即可以对指定文件内容进行全局替换替换完毕后打印替换了多少处内容
#Python学习交流群:531509025import sysimport os if len(sys.argv) != 4:    print("usage: python3 replace old_str new_str filename")    sys.exit()else:    old_str = sys.argv[1]    new_str = sys.argv[2]    filename = sys.argv[3]    filename_swap = sys.argv[3] + ".swap"    with open(filename,"r",enCoding="utf-8") as read_f,open(filename_swap,"w",enCoding="utf-8") as write_f:        count = 0        for line in read_f:            line = line.replace(old_str,new_str)            write_f.write(line)            num = line.count(new_str)            count += 1            totle = count * num        print("一共替换了%s处内容" % totle)    os.remove(filename)    os.rename(filename_swap,filename)

四.模拟登陆:

用户输入帐号密码进行登陆用户信息保存在文件内用户密码输入错误三次后锁定用户,下次再登录,检测到是这个用户也登录不了

user_List.txt

wss:123:1alex:456:1jay:789:1
import getpassimport os user_dict = {}with open("user_List.txt", "r", enCoding="utf-8") as user_List_flIE:    for line in user_List_flIE.readlines():        user_List = line.strip().split(":")        # print(user_List)        _user = user_List[0].strip()        _pwd = user_List[1].strip()        _lockaccount = int(user_List[2].strip())        user_dict[_user] = {"user": _user, "pwd": _pwd, "lockaccount": _lockaccount}        # print(user_dict[_username])        # print(user_dict) exit_flag = Falsecount = 0while count < 3 and not exit_flag:    user = input('\n请输入用户名:')    if user not in user_dict:        count += 1        print("\n用户名错误")    elif user_dict[user]["lockaccount"] > 0:        print("\n用户已被锁定,请联系管理员解锁后重新尝试")        break    else:        while count < 3 and not exit_flag:            pwd = getpass.getpass('\n请输入密码:')            # pwd = input('\n请输入密码:')            if pwd == user_dict[user]["pwd"]:                print('\n欢迎登陆')                print('..........')                exit_flag = True            else:                count += 1                print('\n密码错误')                continue    if count >= 3:  # 尝试次数大于等于3时锁定用户        if user == "":            print("\n您输入的错误次数过多,且用户为空")        elif user not in user_dict:            print("\n您输入的错误次数过多,且用户 %s 不存在" % user)        else:            user_dict[user]["lockaccount"] += 1            # print(user_dict[user]["lockaccount"])            with open("user_List.txt", "r", enCoding="utf-8") as user_List_file, open("use_List.txt.swap", "w",enCoding="utf-8") as new_user_List_file:                for new_line in user_dict:                    new_user_List = [str(user_dict[new_line]["user"]), str(user_dict[new_line]["pwd"]),                                     str(user_dict[new_line]["lockaccount"])]                    # print(new_user_List)                    user_str = ":".join(new_user_List)                    print(user_str)                    new_user_List_file.write(user_str + "\n")            os.remove("user_List.txt")            os.rename("use_List.txt.swap", "user_List.txt")            print("\n您输入的错误次数过多,%s 已经被锁定" % user)
总结

以上是内存溢出为你收集整理的4道Python文件 *** 作函数练习题全部内容,希望文章能够帮你解决4道Python文件 *** 作和函数练习题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1185803.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存