Rodrigo Monteiro Rodrigo Monteiro - 6 months ago 9
Python Question

Writing in text file with python under a given condition

I'm a newbie in python and I'm trying to write a given sentence in a text file using python:

This is my file, and I want to write "T T T" in the lines after "Direct"
if the third column is higher than a given value:

Cu Pd
3.87100000000000
1.0000000000000000 0.0000000000000000 0.0000000000000000
0.0000000000000000 1.0000000000000000 0.0000000000000000
0.0000000000000000 0.0000000000000000 1.0000000000000000
Cu Pd
1 3
Selective dynamics
Direct
-0.0042765297000522 -0.0042765297000522 -0.0042765297000522
-0.0038509734526576 0.4960637515763522 0.4960637515763522
0.4960637515763522 0.4960637515763522 -0.0038509734526576
0.4960637515763522 -0.0038509734526576 0.4960637515763522


For example: If the third column "x" has a value higher than 1.00, it will receive "T T T" after the column, otherwise will receive "F F F".

Any suggestion to where can I start?
Thank you!

Answer

Might want to look at something like this. It reads from one file and writes to another. It only starts examining the contents after 'Direct' is encountered. It should get you started on how to proceed.

def modFile(inPath, outPath, threshold):
    direct = False;
   try:
       # open input file
       with open(inPath, 'r') as ifp:
           # open output file
           with open(outPath, 'w', 'w') as ofp:
                # read each line.
                for line in ifp:
                    if not direct:
                        if line == 'Direct':
                            direct = True
                    else:
                        parts = line.split()
                        # check third value
                        if parts[2] > threshold:
                            line += ' T T T'
                    ofp.write(line + '\n')
    except IOError, e:
        print("Can't read or write from one of the files.")
        # handle in some way
        raise

It's probably only a starting place for solving your full problem but should give you some threads to pull on.

Comments