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
      • 7
      • 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
      • 16
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19

  • Writing to file

    In Python, we can open a file for different purposes. We can read from a file, we can write to it, or we can even append it to the file. To accomplish these tasks, we need to open the file in different modes. The default mode is r (read) which we have been using so far.
    Read (the default one)
    with open('document.txt', 'r') as f:
    with open('document.txt', 'w') as f:
    with open('document.txt', 'a') as f:
    Read + Write
    with open('document.txt', 'r+') as f:
    Create (error if present)
    with open('document.txt', 'x') as f:
    After opening the file with the right mode, we can perform appropriate operations like reading from a file or writing to it. We can write to a file with a write() function:
    with open('document.txt', 'w') as f:
    	f.write('This is a written line\n')
    	f.write('And the second line!')
    	f.write('Continuation is here...')
    After the execution of this program document.txt will contain two lines (because of the \n at the end of the first string). We could have done the writing with a single write() operation, but for the sake of demonstrating, the above program writes several strings to the opened file in separate wirte() commands.


    Given two lines in the input, write a program that would output those lines in output.txt separated by a space.
    hello there
    hello there
    To check your solution you need to sign in
    Sign in to continue