I'm trying to generate 1000 new files from already existing 1000 files in a folder named as 'mdp' into a new folder 'mdb', changing couple of lines in each of the original 1000 files. I took some help from overflow and @bruno desthuilliers suggested me to use this particular code but it hasn't worked yet and it says dest.write(line) AttributeError: 'str' object has no attribute 'write'. I'm kind of new to programming. Could anyone please tell me what am I missing?
import os
sourcedir = "/home/abc/xyz/mdp/"
destdir = "/home/abc/xyz/mdb/"
for filename in os.listdir(sourcedir):
if not filename.endswith(".mdp"):
continue
source = os.path.join(sourcedir, filename)
dest = os.path.join(destdir, filename)
fin = open("/home/abc/xyz/mdp/md_1.mdp")
fout = open("/home/abc/xyz/mdb/md_1.mdp", "w")
for line in source:
line = line.replace('integrator = md', 'integrator = md-vv')
line = line.replace('dt = 0.001', 'dt =
-0.001')
dest.write(line)
2 Answers 2
You messed up with path (which str) and file objects (which a readable/writable), so you've to fix a bit your code:
with open(source) as fin, open(dest, "w") as fout:
for line in fin:
fout.write(
line.replace(
'integrator = md',
'integrator = md-vv',
).replace(
'dt = 0.001',
'dt = -0.001',
)
)
also use with to properly close opened files in case of runtime errors.
Comments
The problem is that dest is a string, not an instance of an open file. The code that I modified should work. Please give it a try and let me know how does it go!
import os
sourcedir = "/home/abc/xyz/mdp/"
destdir = "/home/abc/xyz/mdb/"
for filename in os.listdir(sourcedir):
if not filename.endswith(".mdp"):
continue
# Gets the fullpath for the source and dest files
source = os.path.join(sourcedir, filename)
dest = os.path.join(destdir, filename)
# Open the files in read and write mode
fin = open(source,"r")
fout = open(dest, "w")
# Creates a list of the lines contained in the 'dest' file
lines = fin.readlines()
# Close the source file as is no longer needed
fin.close()
# Loop over each line to implement the modifications
for line in lines:
line = line.replace('integrator = md', 'integrator = md-vv')
line = line.replace('dt = 0.001', 'dt =
-0.001')
# Writes the replaced line into the 'dest' file
fout.write(line)
# Close the 'dest' file after finishing looping
fout.close()
Also, the code that you posted has some indentation issues, I fixed them here.
finvar instead ofsource