fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Working with multiple files

    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 doc1.txt with an r (read) mode and doc2.txt with a w (write) mode. Several open operations are separated by a comma. In the body of the with block, all the opened files are accessible and we can perform different operations on them.

    Challenge

    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.txt and 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.txt that are also present in students.txt.
    source.txt
    student.txt
    Output
    Line 1 Line two
    Line is important
    33.333333
    Explanation: There are 3 unique words in source.txt (Line, 1, two). The word Line is also present in student.txt therefore 33.33333% of words of the source.txt is present in the second file as well.
     
    To check your solution you need to sign in
    Sign in to continue