find in file and replace

I have a file, containing numbers and strings, like this.

1
something ASDF 1,2,3,4,5
2
something2 ASDFG 1,2,5,8,9
etc

between something and ASDF there is a tab

I would like to write two tabs after the "simple" lines. output should be the same:

1\t\t
something ASDF 1,2,3,4,5
2\t\t
something2 ASDFG 1,2,5,8,9
etc

How can I do this?

Upvotes: 1

Views: 91

Answers (4)

Rich Tier
Rich Tier

Reputation: 9441

in 2 lines:

with open('f1') as f:
    ['%s%s' % (l.strip(), '\t\t' if l[0].isdigit() else '') for l in f]

Upvotes: 0

nst
nst

Reputation: 3882

a three lines solution

with open('a-file') as f:
    for i, l in enumerate(f):
        print "%s%s" % (l[:-1], '\t\t' if i % 2 == 0 else '')

Upvotes: 0

falsetru
falsetru

Reputation: 369124

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)

str.isdigit()

regular expression alternative: if re.search('^\d+$', line) != None

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45662

Try this:

#!/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()

output (cortesy of cat -t):

1^I^I
something ASDF 1,2,3,4,5
2^I^I
something2 ASDFG 1,2,5,8,9
etc

Upvotes: 2

Related Questions