- CopyTool练习
'''
练习,利用b模式,编写一个cp工具,要求如下:
1. 既可以拷贝文本又可以拷贝视频,图片等文件
2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file
提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数
'''
import sys
if len(sys.argv) != 3:
print('usage: cp source_file target_file')
sys.exit()
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)
print(type(sys.argv[1]))
# with open("source.jpeg",'rb') as read_f,open("target.png",'wb') as write_f:
# for line in read_f:
# write_f.write(line)
- 光标移动练习
"""
练习:基于seek实现动态监测文件中是否有新内容的添加
"""
import time
with open('a.txt', 'rb') as f:
f.seek(0, 2)
while True:
line = f.readline()
if line:
print(line.decode('utf-8'))
print(f.tell())
else:
time.sleep(2)
print(f.tell())
- 文件更改练习
"""
1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数,求出本次购物花费的总钱数
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
2. 修改文件内容,把文件中的mac都替换成linux
"""
import os
with open("a.txt", "r") as read_f:
read_f = read_f.read()
items = read_f.replace("\n", " ")
item_lst = items.split()
s = 0
for i in range(1, len(item_lst) + 1, 3):
amount = int(item_lst[i]) * int(item_lst[i+1])
s += amount
print("本次购物总金额为:", s)
with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
for line in read_f:
line=line.replace('mac','linux')
write_f.write(line)
os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')
网友评论