0

I have a 1000 files in a folder named md_1.mdp, md_2.mdp, ..., md_1000.mdp and the 186th line of every file reads:

    gen_seed                 = 35086

This value is different in every file and it is what I want to extract and print as the output. I have written the following code but it is not displaying any output.

    import numpy as np
    idx = np.arange(1,1000)
    for i in idx:
       f = open('/home/abc/xyz/mdp_200/md_'+str(i)+'.mdp','r')
       l = f.readlines()
       l = l[185].split(" ")
       flag = 0
       for k in l:
           if flag==1:
               if k!='':
                   print(k)
                   flag=0
           if k=="t=":
               flag=1
       f.close()

What should I add to this program so that it prints the required value for each file one by one in the order of md_1.mdp, md_2.mdp and so on?

1
  • Have you tested if the files open? If the lines are read? If there is an exact text t= anywhere in that line? Commented Apr 4, 2020 at 11:31

1 Answer 1

1

you can use:

for i in range(1, 1001):
    with open('/home/abc/xyz/mdp_200/md_'+ str(i)+ '.mdp') as fp:
        l = fp.readlines()
        print(l[185].split('=')[-1].strip())

or you can use linecache.getline:

import linecache

for i in range(1, 1001):
    file = f'/home/abc/xyz/mdp_200/md_{i}.mdp'    
    line = linecache.getline(file, 185)
    print(line.split('=')[-1].strip())

after you get your line the split is done by = character

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.