Click here to Skip to main content
15,563,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear friends,

I have a code that does some modification on a file(for example; it gives "BTMA1.gro" and get "" with some modification on it). I want to use this code for multiple files( more than 50 similar files but different in numbers " BTMA1.gro, BTMA2.gro , ... with final result as,, ...) how can I change my code for that purpose? I know my code is not very efficient and is long unnecessarily, because I am very beginner but it works. I tried:
[f"BTMA{i}.txt" for i in range(1,50)]

with some other changes but it didn't work and made me more confused. Is it possible for my file to be changed for multiple files? My code is like bellow:

What I have tried:

import re

with open("BTMA1.gro") as infile:
    text =
text = [ re.sub(r'\s+',' ', t) for t in text ]
text = [ re.sub(r'^\s','', t) for t in text ]
with open("BTMA1.gro",'w') as outfile:
import os
import csv

with open('BTMA1.gro') as text_file, open('BTMA2.gro', 'w',newline='') as revised_file:
    reader = csv.reader(text_file, delimiter=' ')
    writer = csv.writer(revised_file, delimiter=' ', quoting=0)

    for idx, row in enumerate(reader, start=1):
        if idx >= 3:
            row.insert(1, row[1][0])
            row[2] = row[2][1:]

os.remove('BTMA1.gro')  # deleted original
os.rename('BTMA2.gro', 'BTMA1.gro')  #renames new to original name   

def fix_line(s):
    dump,x,dump,*nums = s.split()
    # x = x.replace('OW', 'O')
    # x = x.replace('HW1', 'H')
    # x = x.replace('HW2', 'H')
    nums = [ float(x)*10 for x in nums]
    return '{} {:12.3f} {:12.3f} {:12.3f}'.format(x,*nums)
data = open("BTMA1.gro").read().splitlines()[1:-1]
new_data = [ data.pop(0) ]
new_data += [ fix_line(line) for line in data]

open("BTMA1.gro", 'w').write('\n'.join(new_data))

from pathlib import Path # to change .txt to .xyz
p = Path("BTMA1.gro")
Updated 5-Jun-21 0:02am

1 solution

You are using hardcoded file names in your program, so you need to change those. So at the beginning of the program you need to create the names based on some other value. For example:
prefix = "BTMA"
for index in range(1, 20): # change the upper limit to your requirements.
    inputName = prefix + str(index) + ".gro"
    outputName = prefix + str(index) + ".xyz"
    with open(inputName) as infile:
    # remaining code follows this line, and needs to be indented

Then you need to change all "BTMA1.gro" references to inputName. And a similar change for the output files.
Share this answer
mohammad rezayani 5-Jun-21 6:04am    
Dear Richard
Thank you very much for your modification.
My problem is solved.
Richard MacCutchan 5-Jun-21 6:05am    
Thanks, you are welcome.

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