Click here to Skip to main content
15,116,815 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear friends,

I would like to write a formula in which two of parameters are called from two separated files and the others are constant.The formula must be applied on each line of files and it goes for the next line. Finally, I want to write results to another file (out4.txt).

My files are like below:

position.xvg:

1.00000

0.63225

0.51708

0.44592

0.38636

velocity.xvg:

1.00000

-0.00285

-0.00290

0.01266

0.00007

I wrote a code like in the code block.

But the result in "out4.txt" is :
<generator object="" g.<locals="">.<genexpr> at 0x0000018B133B4EC8>

I dont know how to write results(calculated numbers) in my output file.

what is the problem? Also, am I right for choosing this method?

Thank you, in advance, for your answers.

Best

What I have tried:

with open("position.xvg" , "r") as f1:
    cn_xx = [float(x) for x in f1.read().splitlines()]

with open("velocity.xvg" , "r") as f2:
    cn_vv = [float(x) for x in f2.read().splitlines()]  
    
zipeed = zip(cn_xx , cn_vv)      # from files
c0_xx = 1      #constant
c0_vv = 1      #constant
delta_t = 10   #constant
m = 18.01      #constant

def  g(c0_xx,cn_xx,cn_vv,c0_vv,m,delta_t):
    
    for i in range(len(cn_xx)):     
        return ((cn_xx/cn_vv) + c0_vv + c0_xx + m + delta_t  for (cn_xx , cn_vv) in zipeed)
    
result = g(c0_xx,cn_xx,cn_vv,c0_vv,m,delta_t) 

with open ("out4.txt" , "w") as out_put:
    print (result, file=out_put)
Posted
Updated 23-Oct-21 9:52am
v4
Comments
Richard MacCutchan 23-Oct-21 12:06pm
   
You cannot return a single result from a loop in that way. You need to redesign your g function.

1 solution

Python
def write_to_file(c0_xx, cn_xx, cn_vv, c0_vv, m, delta_t):
    with open("my_file.txt", "a") as write_file:
        for i in range(len(cx_xx):
            # I know the formula here is wrong, but you would need to undo it to for the for loop
            write_file.write((cn_xx/cn_vv) + c0_vv + c0_xx + m + delta_t  for (cn_xx , cn_vv) in zipeed))



things to note

1. I haven't tested this
2. the "a" is for appending and "w" is for replacing

for further info Python File Write[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900