首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python:正则表达式+文件处理

一、正则表达式

1.用法:使用Python的re模块,首先用re.compile() 函数,将正则表达式的字符串形式编译为Pattern实例,然后通过Pattern实例处理文本并获得匹配结果(Match实例),再通过Match实例做其他操作。

2.re模块中的match方法:只匹配字符串开始处的字符。3.re模块中的search方法:会匹配整个字符串。'''

# 1

pattern = re.compile('[a-zA-Z]')

match = pattern.findall('ddhfsaqugfa3412hdh21hhdGAAASAA')

print(match)

# 2

print(re.match('\d0','30ddd'))

# 3

print(re.search('\d0','ddd30ddd40ffff50hhh'))

# 1

pattern = re.compile('[a-zA-Z]')

match = pattern.findall('ddhfsaqddDDa3412h21hdGAA')

print(match)

# 2

print(re.match('\d0','30ddd'))

# 3

print(re.search('\d0','ddd30ddd40ffff50hhh'))

二、文件处理

1.打开文件:用open函数,参数为文件路径和打开方式,打开文件返回为fileObject类型

2.读取文件:read函数来处理fileObject类型文件

3.open(path,'x') x = w 是写(原文覆盖),x = r 是读 x = a 写(原文后面追加)

4.换行写入:在要写入的字符串前加/n

5:读写特定编码的文章:open(path,'r',encoding='gbk/utf-8')

6:读写一行:readline() readlines() writelines()

7:工程中出现异常,和安全性考虑:用with

path ='C://Text2.txt'

path1 ='C://Text3.txt'

# 1

file =open(path,'a')

# 2 3

file.write('嘻嘻嘻嘻')

file =open(path,'r')

print(file.read())

file =open(path,'a')

# 4

print(file.write('\njjjjj'))

file =open(path1,'w')

str_list = ['hello\n','world\n','hello hhh\n']

# 6

new_file = file.writelines(str_list)

print('new_file:',new_file)

file =open(path1,'r')

print('file.read:',file.read())

file =open(path1,'r')

print('file.readlines:',file.readlines())

path2 ='C://Text4.txt'

# 7

with open(path2,'w')as f:

print('write length:',f.write('hello world'))

path ='C:/Text2.txt'

path1 ='C:/Text3.txt'

# 1

file =open(path,'a')

# 2 3

file.write('嘻嘻嘻嘻')

file =open(path,'r')

print(file.read())

file =open(path,'a')

# 4

print(file.write('\njjjjj'))

file =open(path1,'w')

str_list = ['hello\n','world\n','hello hhh\n']

# 6

new_file = file.writelines(str_list)

print('new_file:',new_file)

file =open(path1,'r')

print('file.read:',file.read())

file =open(path1,'r')

print('file.readlines:',file.readlines())

path2 ='C:/Text4.txt'

# 7

withopen(path2,'w')asf:

print('write length:',f.write('hello world'))

今天先放点最简单的内容,以后用户多的话可能就每天更新了。

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180503G1FAJN00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券