我有一个文件,包含数字和字符串,就像这样。
1
something ASDF 1,2,3,4,5
2
something2 ASDFG 1,2,5,8,9
etc
在某物和 ASDF 之间有一个标签
我想在“简单”行之后写两个标签。输出应该相同:
1\t\t
something ASDF 1,2,3,4,5
2\t\t
something2 ASDFG 1,2,5,8,9
etc
我怎样才能做到这一点?
尝试这个:
#!/usr/bin/env python
with open('f1') as fd:
for line in fd:
if line[0].isdigit():
print line.strip() + '\t\t'
else:
print line.strip()
输出(由 提供cat -t
):
1^I^I
something ASDF 1,2,3,4,5
2^I^I
something2 ASDFG 1,2,5,8,9
etc
with open('a-file', 'r+') as f:
lines = []
for line in f:
if line.strip().isdigit():
line = line.rstrip() + '\t\t\n'
lines.append(line)
f.seek(0)
f.writelines(lines)
正则表达式替代:if re.search('^\d+$', line) != None
三行解决方案
with open('a-file') as f:
for i, l in enumerate(f):
print "%s%s" % (l[:-1], '\t\t' if i % 2 == 0 else '')
两行:
with open('f1') as f:
['%s%s' % (l.strip(), '\t\t' if l[0].isdigit() else '') for l in f]