我有一个很大的文本文件,其内容格式如下,我想删除两个第一个字符 11,我尝试通过不知道如何继续我的代码进行搜索。寻求帮助。谢谢
文件.txt
11112345,67890,12345
115432,a123q,hs1230
11s1a123,qw321,98765321
342342,121sa,12123243
11023456,sa123,d32acas2
我的代码
import re
with open('in.txt') as oldfile, open('out.txt', 'w') as newfile:
for line in oldfile:
removed = re.sub(r'11', '', line[:2]):
newfile.write(removed)
Run Code Online (Sandbox Code Playgroud)
预期结果:
112345,67890,12345
115432,a123q,hs1230
s1a123,qw321,98765321
342342,121sa,12123243
023456,sa123,d32acas2
这是一个易于阅读的解决方案的建议,不使用正则表达式,我觉得这里有点麻烦(但这显然是个人意见):
with open('in.txt', 'r') as oldfile, open('out.txt', 'w') as newfile:
for line in oldfile:
newfile.write(line[2:] if line.startswith('11') else line)
Run Code Online (Sandbox Code Playgroud)
line[6] != ','在 @kng 的评论后添加了注释:当逗号之前只有 6 个字符时,您可以使用附加条件来避免删除“11”。