Dear friends,
I have a code that does some modification on a file(for example; it gives "BTMA1.gro" and get "BTMA1.xyz" 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 BTMA1.xyz, BTMA2.xyz, ...) 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 = infile.read().splitlines()
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:
outfile.write('\n'.join(text))
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:]
writer.writerow(row)
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.append("XYZ")
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")
p.rename(p.with_suffix(".xyz"))