I need to edit a certain file for a DoE study. The file is in the format:
1 Wall1
roughness 0.0
velocity 0.0
temperature "temperature.file"
########
2 Wall2
roughness 0.0
velocity 0.0
temperature "temperature.file"
########
3 Wall3
roughness 0.0
velocity 0.0
temperature "temperature.file"
########
4 Wall4
roughness 0.0
velocity 0.0
temperature 34.1
########
5 Roof
roughness 0.0
velocity 0.0
temperature "temperature.file"
########
For the DoE, I would like to change one or more "temperature.file" entries (which is a spatially varying temperature field of a region) for each case. So for example, case 2 would have Wall2's temperature file changed to "temperature2.file". The program will then know to find the new file instead of the original.
I have established the nested for loop, but struggling with the file I/O. The code that I have now is:
if m == 2:
with open(newfolder2+'/walls.in','r') as file:
filedata = file.readlines()
for line in filedata:
if 'Wall2' in line:
for line in filedata:
if 'temperature' in line:
print line
line = line.replace('temperature.file','temperature2.file')
print line
break
# file.seek(0)
with open(newfolder2+'/walls.in','w') as file:
file.writelines(filedata)
So essentially I want to to find the line where "Wall2" occurs, then look for the line with temperature after Wall2, then change that, and only that line's "temperature.file" string to "temperature2.file". Then exit the file, and then write to the file, thus creating the new input file for that particular case.
The first print line I have does print out the original line, and the second print line code also correctly prints out the altered line. However, it just seems that the file data isn't being written successfully back to the file.
What seems to be going wrong?
An alternative method, instead of all the nested loops to find a particular line, I thought, was to just use the file.seek() option. The lines and total length of the walls.in file will stay the same, so I can just go straight to that particular line to change the "temperature.in" string. Is this a better approach? I've never tried this, so some sample code would be greatly appreciated.
Thank you all very much!