Skip to content

Exercises

Exercise 16

Save your code in your Python folder and call it exercise16.

Write a program that will:

  • open the file words.txt located on ClassesICT;
  • read its content;
  • print its content;
  • close it.
Help
  • To open a file in read-only:
🐍 Python Script
my_file = open(r"pathToYourFile\file.txt", "r")
content = my_file.read()
print(content)
my_file.close()

Exercise 17

Save your code in your Python folder and call it exercise17.

Write a program that will:

  • open a txt file located on your personal drive;
  • write some content in it;
  • close it.
Help

To write in a file, you can choose to open it in append mode using "a" or in write mode using "w". If you open in write mode, it will erase the previous content of the file, if you open it in append mode, it will add the new content at the end of the file.

Exercise 18

Save your code in your Python folder and call it exercise18.

Write a function getWord(file) that receives the path to a file in parameter and returns one word randomly selected from that file.

Then, write a program that:

  • sets the file variable to the path of the file words.txt located on Classes ICT;
  • calls the function getWord(file);
  • print the word randomly selected.
Help
  • When you read a file, you get one big string with the entire content of the file. To transform the content into a list where each element of the list is a line of the file, you just need to split the string on "\n":

content = content.split("\n")

  • To randomly select one element from a list, don't forget to import random and type:

my_list[random.randint(0,(len(my_list)-1)]