python3——文件IO效率相关问题与解决技巧——python2和python3读写文件的区别

1. python2和python3的字符串语义区别

     str           ———》 bytes

     unicode  ———》 str

     chr():十进制或十六进制数(0-255)转成对应的ASCII字符.

     ord():ASCII字符转成对应的十进制数.

    生成随机验证码

     import random
     def make_code(size=7):
          res = ''
          for i in range(size):
              # 循环一次则得到一个随机字符(字母/数字)
             s = chr(random.randint(65, 90))
             num = str(random.randint(0, 9))
            res += random.choice([s, num])
          return res

     res=make_code()
     print(res)

2. python2读写文件,写入时,需要先进行编码, 读出时,需要进行解码

    

3. python3读写文件

s= u"明日复明日,明日何其多,我待复明日,往事成蹉跎"
print(type(s))
f=open("test.txt","w",encoding='gbk')
f.write(s)
f.flush
f=open('test.txt',encoding='gbk')
print(f.read())
原文地址:https://www.cnblogs.com/ting152/p/12602991.html