美文网首页
第五章文件处理

第五章文件处理

作者: 我在你_1a19 | 来源:发表于2019-01-28 23:57 被阅读0次
    1. 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)
    
    1. 光标移动练习
    
    """
    练习:基于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. 文件更改练习
    """
    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')
    
    

    相关文章

      网友评论

          本文标题:第五章文件处理

          本文链接:https://www.haomeiwen.com/subject/qgktsqtx.html