首页 > 编程语言 > 详细

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

时间:2020-03-31 13:11:01      阅读:81      评论:0      收藏:0      [点我收藏+]

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())

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

原文:https://www.cnblogs.com/ting152/p/12602991.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!