一.利用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)

  

  

第3章 Python基础-文件操作&函数 文件操作 练习题的更多相关文章

  1. [Python笔记][第一章Python基础]

    2016/1/27学习内容 第一章 Python基础 Python内置函数 见Python内置函数.md del命令 显式删除操作,列表中也可以使用. 基本输入输出 input() 读入进来永远是字符 ...

  2. python基础——内置函数

    python基础--内置函数  一.内置函数(python3.x) 内置参数详解官方文档: https://docs.python.org/3/library/functions.html?highl ...

  3. python学习第五讲,python基础语法之函数语法,与Import导入模块.

    目录 python学习第五讲,python基础语法之函数语法,与Import导入模块. 一丶函数简介 1.函数语法定义 2.函数的调用 3.函数的文档注释 4.函数的参数 5.函数的形参跟实参 6.函 ...

  4. 自学Python之路-Python基础+模块+面向对象+函数

    自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python    1.1 自学Python1.1-简介    1.2 自学Python1.2-环境的 ...

  5. python基础——高阶函数

    python基础——高阶函数 高阶函数英文叫Higher-order function.什么是高阶函数?我们以实际代码为例子,一步一步深入概念. 变量可以指向函数 以Python内置的求绝对值的函数a ...

  6. 0003.5-20180422-自动化第四章-python基础学习笔记--脚本

    0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...

  7. python基础之元组、文件操作、编码、函数、变量

    1.集合set 集合是无序的,不重复的,主要作用: 去重,把一个列表变成集合,就可以自动去重 关系测试,测试两组数据的交集,差集,并集等关系 操作例子如下: list_1 = [1,4,5,7,3,6 ...

  8. Python-Day3 Python基础进阶之集和/文件读写/函数

    一.集和 集合是一个无序的,不重复的数据组合,它的主要作用如下: 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之前的交集.差集.并集等关系 1.创建集合 >>> s ...

  9. Python基础(七)-文件操作

    一.文件处理流程 1.打开文件,得到文件句柄赋值给一个变量 2.通过句柄对文件进行操作 3.关闭文件 二.基本操作 f = open('zhuoge.txt') #打开文件 first_line = ...

随机推荐

  1. thinkphp3返回json或jsonp数据

    1.返回json数据 public function demo1() { $data = 'ok'; $this->ajaxReturn($data); } public function de ...

  2. Binary Search二分法搜索C++程序

    二分法基本上学计算机的都听过,但是有人不知道的就是其实二分法是减治法的思想. 所谓减治法和分治法有一个主要差别就是减治法是减去一般,就是分治之后只需要解决原问题的一半就可以了得到全局问题的解了.所以速 ...

  3. __builtin_constant_p

    int __builtin_constant_p (exp); You can use the built-in function __builtin_constant_p to determine ...

  4. bootstrap找不到glyphicons-halflings-regular.woff2

    在vue2的项目中是用bootstrap,提示下面的字体文件找不到 http://localhost:8080/static/fonts/glyphicons-halflings-regular.wo ...

  5. python object对象

    动态语言的对象属性 既然都是动态语言,自然python和熟知的JavaScript很像,建一个空对象用来存放所有的数据,看看js: var data = {}; data.name = 'CooMar ...

  6. GitHub如何下载clone指定的tag

    如上图,我想下载Tags标签为solution-4 的代码,如何处理呢? 命令如下: git clone --branch solution-4 git@github.com:zspo/learngi ...

  7. 单页面SPA应用路由原理 history hash

    <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8&quo ...

  8. 【leetcode】solution in java——Easy5

    转载请注明原文地址: 21:Assign Cookies Assume you are an awesome parent and want to give your children some co ...

  9. Java ConcurrentHashMap (Java代码实战-005)

    package Threads; import com.google.common.collect.Maps; import java.util.concurrent.ConcurrentMap; i ...

  10. 我的第一个android应用——装逼神器《微博尾》

    继<微博尾>之<玩转尾巴>好玩尾巴积分版传送门:http://blog.csdn.net/love_5209/article/details/39473983 (本文andro ...