Greg
Greg

Reputation: 257

Writing certain contents from one file to another in python

I have a file that I need to write certain contents to a new file.

The current contents is as follows:

send from @1373846594 to pool/10.0.68.61@1374451276 estimated size is 7.83G
send from @1374451276 to pool/10.0.68.61@1375056084 estimated size is 10.0G

I need the new file to show:

@1373846594 --> pool/10.0.68.61@1374451276 --> 7.83G
@1374451276 --> pool/10.0.68.61@1375056084 --> 10.0G

I have tried:

with open("file", "r") as drun:
    for _,_,snap,_,pool_,_,_,size in zip(*[iter(drun)]*9):
        drun.write("{0}\t{1}\t{2}".format(snap,pool,size))

I know I am either way off or just not quite there but I am not sure where to go next with this. Any help would be appreciated.

Upvotes: 2

Views: 122

Answers (4)

edi_allen
edi_allen

Reputation: 1872

SOURCE, DESTINATION, SIZE = 2, 4, 8    
with open('file.txt') as drun:
    for line in drun:
        pieces = line.split()
        print(pieces[SOURCE], pieces[DESTINATION], pieces[SIZE], sep=' --> ', file=open('log.txt', 'a'))

Upvotes: 0

Nick Burns
Nick Burns

Reputation: 983

Perhaps something simple using a regex pattern match:

with open('output_file', 'w') as outFile:
    for line in open('input_file'):
        line = line.split()
        our_patterns = [i for i in line if re.search('^@', i) or \
                                           re.search('^pool', i) or \
                                           re.search('G$', i)]

        outFile.write(' --> '.join(our_patterns) + '\n')

The pattern matching will extract any parts that begin with @ or pool, as well as the final size that ends with G. These parts are then joined with the --> and written to file. Hope this helps

Upvotes: 0

David.Zheng
David.Zheng

Reputation: 913

inf = open(file)
outf = open(outfile,'w')
for line in inf:
    parts = line.split()
    outf.write("{0}-->{1}-->{2}".format(parts[2], parts[4], parts[8]))

inf.close()
outf.close()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You want to split your lines using str.split(), and you'll need to write to another file first, then move that back into place; reading and writing to the same file is tricky and should be avoided unless you are working with fixed record sizes.

However, the fileinput module makes in-place file editing easy enough:

import fileinput

for line in fileinput.input(filename, inplace=True):
    components = line.split()
    snap, pool, size = components[2], components[4], components[-1]
    print '\t'.join((snap,pool,size))

The print statement writes to sys.stdout, which fileinput conveniently redirects when inplace=True is set. This means you are writing to the output file (that replaces the original input file), writing a bonus newline on every loop too.

Upvotes: 1

Related Questions