Python学习之文件读写、正则表达式

一:写文件

# 文件读写

strs = 'tjf is 18,pretty good'

#操作文件时常见的错误类型
# ValueError: must have exactly one of create/read/write/append x/r/w/a mode

fp = open("./data.txt", 'a', encoding='utf-8')

fp.write(strs + "\n")

fp.close()

# 读取一个图片 然后写出去
# 读二进制 写二进制没有encoding,因为是图片
fp_r = open(r"C:\Users\shujia\Pictures\wallhaven-6dg7ll.png", 'rb')
png_content = fp_r.read()
print(png_content)
fp_r.close()
fp_w = open("./xxx.png", 'wb')
fp_w.write(png_content)
fp_w.close()

# 整个代码内只需要打开或者写一次  建议使用with open
# 如果全代码好几个地方需要写 建议使用 open
with open("./data.txt", 'r', encoding='utf-8') as fp:
    print(fp.readlines())

二:正则表达式1

import re

# 正则表达式
# 1、用一些字符去描述字符
# 2、如果直接给出字符就是精确匹配
a = 'wy'
print(re.match('wy', a))
# \d 匹配一个数字字符
print(re.match('\d\d\d', '012'))
# \w 匹配一个字母或者数字 和 _
print(re.match('\w\w\w', '01A'))
# . 可以匹配任意字符 除\n
print(re.match('...', 'w12'))
# \s 可以匹配任意空白字符 、 换页、 换行、 制表符
print(re.match('\s\s\s\s', ' \n\t\f'))

# 匹配个数符号  {num} 表示匹配这么多 少了返回空 多了返回num长度(最大长度)
print(re.match('\d{11}', '0123413131231'))
print(re.match('\d{8,11}', '0123413131231'))

# 0551-1234567 010-1234567 匹配电话号码
print(re.match('\d{3,4}-\d{7}', '010-1234567'))
# * 匹配任意长度的字符
# + 匹配至少一个字符
# ? 匹配0或1个字符

# 匹配一个变量名,不能以数字开头
print(re.match('[a-zA-Z_]\w*', 'a_b'))
print(re.match('[Pp]ython', 'Python'))

s = 'ABC\\-001'
print(re.match(r"\w+\\-\d+", s))


s = "Hello 1234567 is a number. Regex String"
print(re.match("Hello (\d*).*", s))

三:正则表达式2

import re

# 正则表达式
# 1、用一些字符去描述字符
# 2、如果直接给出字符就是精确匹配
a = 'wy'
print(re.match('wy', a))
# \d 匹配一个数字字符
print(re.match('\d\d\d', '012'))
# \w 匹配一个字母或者数字 和 _
print(re.match('\w\w\w', '01A'))
# . 可以匹配任意字符 除\n
print(re.match('...', 'w12'))
# \s 可以匹配任意空白字符 、 换页、 换行、 制表符
print(re.match('\s\s\s\s', ' \n\t\f'))

# 匹配个数符号  {num} 表示匹配这么多 少了返回空 多了返回num长度(最大长度)
print(re.match('\d{11}', '0123413131231'))
print(re.match('\d{8,11}', '0123413131231'))

# 0551-1234567 010-1234567 匹配电话号码
print(re.match('\d{3,4}-\d{7}', '010-1234567'))
# * 匹配任意长度的字符
# + 匹配至少一个字符
# ? 匹配0或1个字符

# 匹配一个变量名,不能以数字开头
print(re.match('[a-zA-Z_]\w*', 'a_b'))
print(re.match('[Pp]ython', 'Python'))

s = 'ABC\\-001'
print(re.match(r"\w+\\-\d+", s))


s = "Hello 1234567 is a number. Regex String"
print(re.match("Hello (\d*).*", s))
  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值