比方说,我有一个文本文件,其中既包含字母数字值,又仅包含长度为10位数字的数字值,如下图所示:
abcdefgh
0123456789
edf6543jewjew
9876543219
我要删除仅包含那些随机的10位数字的所有行,即上述示例的预期输出如下:
abcdefgh
edf6543jewjew
如何在Python 3.x中做到这一点?
答案 0 :(得分:3)
with open("yourTextFile.txt", "r") as f:
lines = f.readlines()
with open("yourTextFile.txt", "w") as f:
for line in lines:
if not line.strip('\n').isnumeric():
f.write(line)
elif len(line.strip('\n')) != 10:
f.write(line)
答案 1 :(得分:1)
打开输入文件,读取所有行,过滤掉仅包含数字的行,然后将过滤后的行写回到新文件中。
import re
with open(input_file_path) as file:
lines = file.readlines()
output_lines = [line for line in lines if not re.match(r'^[0-9]+$', line.strip('\n'))]
with open(output_file_path, 'w') as file:
file.write('\n'.join(output_lines))
答案 2 :(得分:-1)
import re
fh=open('Desktop\Python13.txt','r+')
content=fh.readlines()
fh.seek(0)
for line in content:
if re.match(r'[0-9]{10}',line):
content.remove(line)
fh.write(''.join(content))
fh.truncate()
fh.close()