python:create file

 

# calculate file size in KB, MB, GB
def convert_bytes(size):    
    """
    Convert bytes to KB, or MB or GB
    :param size
    :return
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024.0:
            return "%3.1f %s" % (size, x)
        size /= 1024.0
def get_size(file_size, unit='bytes'):
    #file_size = os.path.getsize(file_path)
    exponents_map = {'bytes': 0, 'kb': 1, 'mb': 2, 'gb': 3}
    if unit not in exponents_map:
        raise ValueError("Must select from ['bytes', 'kb', 'mb', 'gb']")
    else:
        size = file_size / 1024 ** exponents_map[unit]
        return str(round(size, 3))+' '+unit

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    #print_hi('PyCharm,python language')
    #创建目录
    #os.mkdir(path)
    filename = '1.py'
    try:
        if not os.path.exists("Common"):
            os.mkdir("Common")
        else:
            if os.path.exists("Common/"+filename):
                print(filename)
                with io.open("Common/" + filename, 'r', encoding='utf8') as f:
                    text = f.read()
                    print(text)
            else:
                os.chdir("Common/")
                with io.open(filename, 'w', encoding='utf8') as f:
                    f.write('#涂聚文\nimport io \n import sys \nimport os \n size=10')
                with io.open("Common/" + filename, 'r', encoding='utf8') as f:
                    text = f.read()
                    print(text)
    except FileNotFoundError:
        print('文件不存在')
    except PermissionError:
        print('权限错误')
    if os.path.exists("Common/"+filename):
        size = os.path.getsize("Common/" +filename)
        creation_time = os.path.getctime("Common/" +filename)
        extension = os.path.splitext("Common/" +filename)[1]
        t = time.localtime(creation_time)
        print(f"{get_size(size,'bytes')},{time.strftime('%Y-%m-%d %H:%M:%S', t)},{extension}")

  

    #同时迭代多个序列
    du=[1,3,8,8]
    ku=[4,9,12,38]
    ju=[8,9,10,18]
    for x,y in zip(du,ku):
        print(x,y)

    for x,y,z in zip(du,ku,ju):
        print(x,y,z)

    # 以索引--值的形式迭代序列
    for idx,val in enumerate(du):
        print(idx,val)

  

posted @ 2024-06-18 23:27  ®Geovin Du Dream Park™  阅读(6)  评论(0编辑  收藏  举报