I am trying to create a function that combines 2 text files, and sorts them, before writing the result to a new file. I have read the existing threads about sorting files, as well as the threads about merging files, but I haven't been able to find one that answers my question.
File1:
12:24:00: 14, 15, 16
20:13:09: 1, 2, 3
File2:
08:06:02: 43, 54, 10
15:16:05: 6, 2, 12
And the desired output would be this:
NewFile:
20:13:09: 1, 2, 3
15:16:05: 6, 2, 12
12:24:00: 14, 15, 16
08:06:02: 43, 54, 10
I originally tried to merge the content of both files into one list, and then sort it, before writing it to a new file, but that didn't seem to work. Here is what I have tried so far:
def mergeandsort(file1, file2, NewFile):
s1, s2, d=open(src1, 'r'), open(src2, 'r'), open(dst, 'w')
l=[]
l.append(list(s1))
l.append(list(s2))
n=sorted(l)
c=''.join(str(n))
d.write(c)
s1.close(); s2.close(); d.close()
I am new to Python, so any help would be appreciated!
Trying to fix your implementation:
def mergeandsort(src1, src2, dst):
# Use `with` statements to close file automatically
with open(src1, 'r') as s1, open(src2, 'r') as s2, open(dst, 'w') as d:
l = list(s1) + list(s2)
l.sort(reverse=true) # Since you seem to want them in reverse order...
c = ''.join(l)
d.write(c)
Note that this is not optimal if you manipulate big files...
Following are step:
Demo:
>>> p1 = '/home/vivek/Desktop/f1.txt'
>>> p2 = '/home/vivek/Desktop/f2.txt'
>>>
>>> fp1 = open(p1)
>>> fp2 = open(p2)
>>> l1 = fp1.read().strip().split("\n")
>>> l1
['12:24:00: 14, 15, 16', '20:13:09: 1, 2, 3']
>>> l2 = fp2.read().strip().split("\n")
>>> l2
['08:06:02: 43, 54, 10', '15:16:05: 6, 2, 12']
>>> l3 = l1+ l2
>>> l3
['12:24:00: 14, 15, 16', '20:13:09: 1, 2, 3', '08:06:02: 43, 54, 10', '15:16:05: 6, 2, 12']
>>> sorted(l3)
['08:06:02: 43, 54, 10', '12:24:00: 14, 15, 16', '15:16:05: 6, 2, 12', '20:13:09: 1, 2, 3']
>>> merge_list = sorted(l3)
>>> merge_list.reverse()
>>> merge_list
['20:13:09: 1, 2, 3', '15:16:05: 6, 2, 12', '12:24:00: 14, 15, 16', '08:06:02: 43, 54, 10']
>>>
Function:
def mergeandsort(file1, file2, output):
fp1, fp2 = open(file1, 'r'), open(file2, 'r')
merge_data = fp1.read().strip().split("\n") + fp2.read().strip().split("\n")
merge_data = sorted(l3, reverse=True)
fp = open(output, 'w')
for i in merge_data:
fp.write(i)
fp.close()
return True, output
p1 = '/home/vivek/Desktop/f1.txt'
p2 = '/home/vivek/Desktop/f2.txt'
p3 = '/home/vivek/Desktop/f12.txt'
print mergeandsort(p1, p2, p3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With