add text in a file with python (without replacing it) -



add text in a file with python (without replacing it) -

i have file ids , information, this:

1omzgkoaz3o 2011-12-29t01:23:00.000z 9 503 apolloismycopilot nuw1tomcsqg 2011-12-29t01:23:15.000z 9 348 grea7stuff tjulnrracs0 2011-12-29t01:26:20.000z 9 123 adelgaming tyi5g0mnpis 2011-12-29t01:28:07.000z 9 703 preferredgaming

and want add together flag on of line, if have dictionary

flags = {'1omzgkoaz3o': flag1, 'tjulnrracs0': flag2}

the result want

1omzgkoaz3o 2011-12-29t01:23:00.000z 9 503 apolloismycopilot flag1 nuw1tomcsqg 2011-12-29t01:23:15.000z 9 348 grea7stuff tjulnrracs0 2011-12-29t01:26:20.000z 9 123 adelgaming flag2 tyi5g0mnpis 2011-12-29t01:28:07.000z 9 703 preferredgaming

so made code

l = true while l true: = f.readline() seek a.split(' ')[0] in flags.iterkeys(): f.seek(-1,1) f.write(' '+str(flags[a.split(' ')[0]])+'\n') del flags[a.split(' ')[0]] except indexerror: l = false

so, python code poor, problem code i'm replacing text, file messed up. how can write without replacing? , if have improve ideas code, welcome...

i see 2 problems here:

reading , writing from/to same file

this doesn't work well. improve read 1 file , write 1 (this way, won't lose info if goes wrong in program). example:

input_file = open('infile.txt', 'r') output_file = open('outfile.txt', 'w') line in input_file: line += "transformed" output_file.write(line) syntactic/semantic errors

you have syntactic error in code snippet, line

try a.split(' ')[0] in flags.iterkeys():

is not valid (and python should complain that!).

some other things note:

in flags.iterkeys() semantically equivalent in flags also, can utilize while l instead of while l true. better, drop flag variable l , jump out of loop break if error occurs. my attempt input_file = open('infile.txt', 'r') output_file = open('outfile.txt', 'w') flags = { ... } line in input_file: parts = line.strip().split() if parts[0] in flags: line = line + ' ' + flags[parts[0]] output_file.write(line + "\n")

if know how utilize shell, create life easier if utilize stdin/stdout info in- , output. save file handling , leave user more flexibility in how can utilize script.

python

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -