I will start off by saying that I have seen the answers to a similar question. I have attempted to use this for my problem, but I am unable to get it to function properly.
I have multiple .xyz
files with the same prefix and suffix starting from 0. There is potential to be 100+ files, so not defining them individually is essential. I need to merge/concatenate/append these files in numerical order to a merged.xyz
. For example:
output0.xyz:
H 1.0 1.0 1.0
output1.xyz:
H 2.0 2.0 2.0
merged.xyz:
H 1.0 1.0 1.0
H 2.0 2.0 2.0
I have tried this as a simple test case:
tempfiles = ['output0.xyz', 'output1.xyz']
f = open("bigtextfile.xyz", "w")
for tempfile in tempfiles:
f.write(tempfile.read())
But I get:
Traceback (most recent call last):
File "Test.py", line 28, in <module>
f.write(tempfile.read())
AttributeError: 'str' object has no attribute 'read'
An alternative I have attempted:
prefix = "output"
suffix = ".xyz"
count = 0
while count <= 1:
for filename in os.listdir('./'):
if filename.endswith(suffix):
xyzFile = open(prefix + str(count) + suffix, "r")
lines = xyzFile.readlines()
xyzFile.close()
merged = open("merged" + suffix, "a")
for line in lines:
merged.write(line)
merged.close()
count += 1
But it copies the first file twice, and the second three times:
H 1.0 1.0 1.0
H 1.0 1.0 1.0
H 2.0 2.0 2.0
H 2.0 2.0 2.0
H 2.0 2.0 2.0
How do you suggest I move forward? I am leaning towards the second solution, as it already automatically gets the contents of the files in numerical order. Please let me know if you need any additional details and how to improve the question.