Fork me on GitHub

第3章 Python基础-文件操作&函数 文件操作 练习题

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

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

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

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

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# cp工具
import sys
if 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 功能

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#tail -f工具
import sys,time
if 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行。

https://www.cnblogs.com/shengxinjing/p/5397145.html

三.文件的修改

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

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(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') 

三.全局替换程序:

  • 写一个脚本,允许用户按以下方式执行时,即可以对指定文件内容进行全局替换

  •  替换完毕后打印替换了多少处内容
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import sys
import 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:1
alex:456:1
jay:789:1
#!/usr/bin/env python3
# -*- encoding: utf8 -*-

import getpass
import 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 = False
count = 0
while 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)

 

  

  

posted @ 2018-03-14 18:00  IT技术随笔  阅读(1069)  评论(0编辑  收藏  举报
返回顶部↑