格式化输出与文件I/O

格式化输出与文件I/O


  1"""
  2Author: wangy325
  3Date: 2024-08-06 11:01:31
  4Description: 
  5"""
  6from math import pi as pi
  7
  8"""
  9输入输出与文件I/O
 101. 格式化字符串
 112. 读取文件
 12"""
 13'''
 14使用占位符
 15'''
 16year = 2024
 17event = 'Trump\'s Gun Shot'
 18print(f'Big News of {event} in {year}')
 19
 20# 或者这样
 21print(f'Big News of {event=} in {year=}')
 22
 23# 占位符支持还格式化字符串输出
 24print(f'The value of pi is approximately {pi:.3f}')
 25
 26# 可以指定宽度
 27table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
 28for name, phone in table.items():
 29    print(f'{name:10} ==> {phone:10d}')
 30'''
 31使用format()方法
 32'''
 33yes_votes = 42_573_651
 34total_votes = 83_637_912
 35percentage = yes_votes / total_votes
 36print('{:-9} YES votes {:2.3%}'.format(yes_votes, percentage))
 37
 38# 或者 加入前导位置索引
 39print('{1:-9} YES votes {0:2.3%}'.format(percentage, yes_votes))
 40
 41# 或者直接使用关键字
 42print('{yes_votes:4} YES votes {percentage:2.3%}'.format(yes_votes=117,
 43                                                         percentage=0.459417))
 44# 还可以直接输出字典类型
 45dicta = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
 46print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**dicta))
 47'''
 48Old school 格式化方法(Java还在用哦)
 49'''
 50print('The value of pi is approximately %5.3f.' % pi)
 51
 52'''
 53读写文件
 54python可以以纯文本或者二进制字节的形式读写文件
 55with 关键字的作用类似Java的try..with...resource, 不需要显式地处理异常和关闭资源
 56如果不使用with关键字, 则需要处理异常 和关闭资源
 57
 58with语句在python中更加强大, 一般称作"上下文管理器"
 59https://docs.python.org/zh-cn/3/reference/compound_stmts.html#the-with-statement
 60'''
 61# ###### #
 62# 文本流  #
 63# ###### #
 64with open('pys/misc/text', '+w', encoding="utf-8") as f:
 65    f.writelines([
 66        '這是一個純文字檔案.\n',
 67        'This is a plain text file.\n'
 68        'これはただのテキストファイルです.\n',
 69        'Il s\'agit d\'un fichier texte brut.\n',
 70        'Este es un archivo de texto sin formato.\n'
 71    ])
 72fil = open('pys/misc/text')
 73while (line := fil.readline()) != '':
 74    print(line, end='')
 75fil.close()
 76
 77# ###### #
 78# 字节流  #
 79# ###### #
 80
 81file_path = 'pys/misc/textb'
 82if not os.path.exists(file_path) or not os.path.isfile(file_path):
 83    open('pys/misc/textb', 'x')
 84with open('pys/misc/textb', '+wb') as fb:
 85    btsw = fb.write(b'This is a binary text file.')
 86    # 文件指针向前移动到写入字节数前一位
 87    fb.seek(btsw - 1)
 88    bt = fb.read(1)
 89    print(bt == b'.')
 90
 91
 92# 试试复制张图片
 93def copy_file(target, dest):
 94    if os.path.exists(target) and os.path.isfile(target):
 95        if not os.path.exists(dest) or not os.path.isfile(dest):
 96            df = open(dest, '+xb')
 97            with open(target, 'rb') as tf:
 98                while len((buffer := tf.read(1024))) > 0:
 99                    df.write(buffer)
100            df.close()
101        else:
102            print("dest file exists.")
103    else:
104        raise FileNotFoundError("target file not found.")
105
106
107copy_file('pys/misc/bot.jpg', 'pys/misc/bot_copy.jpg')