• Python_usetxt


    # 文件操作
    
    file.readline() # 读取一行
    file.read(num) # 读取多少字符
    file.readlines() # 读取多行,结果以列表形式返回
    
    file = open('test.txt', 'r', encoding='utf-8')
    for line in file.readlines():
        print(str(line).strip())
    
    file.close() # 关闭文件
    
    # 打印所有行,另外第3行后面加上end3
    number = 0
    for line in file:
        if number == 3:
            line = ''.join([line.strip(), 'end 3')
        print(line.strip())
        number += 1
    
    for  index, line in enumerate(file.readlines):
        if index == 2:
            line = ''.join([line.strip(), 'end 3')
        print(line.strip())
    
    file.tell() # 反映当前所处的文件位置
    file.seek(num) #  跳到文件的任何位置 ,主要的功能跳到文件的开头
    
    file.flush() # 刷新
    
    #!/usr/bin/env python3
    # _*_ coding:utf-8 _*_
    # ========================================================
    # Module         :  progress_bar
    # Author         :  luting
    # Create Date    :  2018/3/12
    # Amend History  :  2018/3/12
    # Amended by     :  luting
    # ========================================================
    
    import sys
    import time
    
    
    def progressbar(fn):
    
        def wrapper(*args, **kwargs):
    
            try:
                sys.stdout.write('Running: {0}
    '.format(fn.__name__))
                for count in range(1, 51):
                    sys.stdout.write("
    [{0}{1}]{2}%".format("" * count, " " * (50 - count), count * 2))
                    sys.stdout.flush()
                    time.sleep(0.3)
                return fn(*args, **kwargs)
            except KeyboardInterrupt:
                raise
    
        return wrapper
    
    if __name__ == '__main__':
    
        @progressbar
        def install_apk():
            pass
        install_apk()
    
        
    file.truncate(file_index) # 清除文件内容
    
    # 文件处理模式
    
    r 以只读的模式打开文件
    w 以只写模式打开文件
    a 以追加模式打开文件
    r+b 以读写模式打开   b二进制的形式处理文件
    w+b 以写读模式打开 
    a+b 以追加及读模式打开
    
    
    以w模式打开的时候如果文件中存在内容,则会把文件覆盖掉
    如果文件不存在,则会创建该文件
    
    不写处理模式,则默认为R的模式
    
    # 修改
    f_r = open(file_name, r, encoding='utf-8')
    f_w = open(file_name, w, encoding='utf-8')
    
    number = 0
    for line  in f_r:
        number += 1
        if number == 5:
            line = 'new line
    '
        f_w.write(line)
    f_r.close()
    f_w.close()
    
    # with
    
    with open(file_name, 'r') as f_r, with open(file_name, 'w') as f_r:
        pass
  • 相关阅读:
    [zz]std::vector,std::deque,std::list的区别的使用
    [zz]有关写c++代码的习惯
    [zz]Ubuntu linux 基本操作 双网卡双IP配置
    [zz]ZooKeeper 典型的应用场景
    [zz]Ubuntu配置双网卡
    java配置文件问题
    Struts2知识积累(2)_核心概念:拦截器
    【双旦献礼】PortalBasic Java Web 应用开发框架 v3.0.1 正式发布(源码、示例及文档)
    hibernate入门
    为Eclipse定制你自己的注释模板变量
  • 原文地址:https://www.cnblogs.com/xiaoxiaolulu/p/8556127.html
Copyright © 2020-2023  润新知