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

  • Working with files in Python

    Files store persistent information on our computers. They’re usually located on our computer's hard drive, which can keep the contents of a file even when the machine is rebooted or turned off. Files have the format name.extension. Examples can include:
    • program.py for a python program file
    • holiday.jpg for a holiday picture
    • Resume.pdf for the PDF CV file
    When working with files, we usually open them, do something with their content, then close the file. The same operations are performed in Python as well. Working with text files can be done in 3 steps:
    f = open('document.txt')   # Open the document.txt file
    print(f.read())            # Read the contents and print them
    f.close()                  # Close the file
    Here f.read() returns all the contents of the file document.txt as a string. We could assign that string to a variable, but in this example, we just print the content.


    There will be a file called input.txt. The program should read the content of input.txt and print:
    • The number of characters in the file
    • The number of lines in the file
    • The number of words in the file (words are separated by a space or a new line)
    each on a separate line.
    hello this is some file content
    31 2 6
    To check your solution you need to sign in
    Sign in to continue