0

I need some help using the fileinput module in Python : I need to replace part of the string, where it's written "1.00", by 'CV'. There are files of thousands of lines, and I want to do this operation only on the files starting with "ATOM". Here is an exemple of the line :

ATOM    143  CB  LYS A  21       6.503  47.292  27.783 1.00 13.27           C

when job is done :

ATOM    143  CB  LYS A  21       6.503  47.292  27.783 CV 13.27           C

The code below do the job, but do not save the results in the file. How can I fix it ? Thank you very much for your help !

Code :

import fileinput

def replace2(fileName):

f = fileinput.input(files=fileName)
for line in f:
    if line.startswith('ATOM'):
           line = line.replace(line[55:60], 'CV')
f.close()

However, I did it in an other way, and this does work. I just wondered if it wasn't faster and more synthetic with fileinput.

Code that works:

def replace(fileName, outFile):
with open(fileName, 'r') as infile, open(outFile, 'w') as outfile :
    for line in infile :
        if line.startswith('ATOM'):
           line = line.replace(line[55:60], 'CV')
        outfile.write(line)
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
Natha
  • 364
  • 1
  • 3
  • 20

0 Answers0