We can open multiple files at once and operate on those together:
with open('doc1.txt') as d1, open('doc2.txt', 'w') as d2: text = d1.read() # Read everything from doc1.txt d2.write(text) # Write the contents to doc2.txt print('Done copying the content')
Here we have opened the
r(read) mode and
w(write) mode. Several
openoperations are separated by a comma. In the body of the
withblock, all the opened files are accessible and we can perform different operations on them.
When developing a similarity detection system, you decide to compare two files together. You would like to know the percentage of the words that are present in both files.
The first file is
source.txtand the second one is the
student.txt. Compute the number of unique words in both files and print the percentage of the unique words in
source.txtthat are also present in
source.txt Line 1 Line two student.txt Line is important Output 33.333333
Explanation: There are 3 unique words in
source.txt(Line, 1, two). The word Line is also present in
student.txttherefore 33.33333% of words of the
source.txtis present in the second file as well.