fb pixel

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.

Challenge

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.
input.txt
hello this is
some file content

Output
31
2
6
 
To check your solution you need to sign in
Sign in to continue