session_10_file_processing
session_10_file_processing
1
Reading From a Text File
• So far, we have seen one forms of input to our code
• Using the input() function to directly ask for user input
• You can upload a file to Google Colab to be read by Python from the
sidebar
2
Reading From a Text File
• We can read the following text file using the syntax below
Resources
3
Reading From a Text File
• We may want to read a text file into a list with one element per line
• There are a few ways to do this. Arguably the easiest is to read the file
as one and the split at each newline character
4
Writing to Text Files
• We can write to a file using the .write() method
• To do this we must add new lines using ‘\n’
• When we open the file we must specify the we are using write mode or
append mode
5
Exercise 1
• Write a program that accepts name of five students and save it to a text
file named student_names.txt
6
Exercise 1 Solution
• Write a program that accepts name of five students and save it to a text
file named student_names.txt
7
Exercise 2
• Now, read the student_names.txt file and display student names line by
line
8
Exercise 2 Solution
• Now, read the student_names.txt file and display student names line by
line
9
Exercise 3
• Now, read and display total number of lines in the student_names.txt file
10
Exercise 3 Solution
• Now, read and display total number of lines in the student_names.txt file
11
Exercise 4
• Write a python program that read a text file about_ethiopia.txt and count
total number of words in the file.
12
Exercise 4 Solution
• Write a python program that read a text file about_ethiopia.txt and count
total number of words in the file.
13
Exercise 5
• Write a python program that read a text file about_ethiopia.txt and count
unique number of words in the file.
14
Exercise 5 Solution
• Write a python program that read a text file about_ethiopia.txt and count
unique number of words in the file.
15
Exercise 6
• Write a python program that read a text file about_ethiopia.txt and
convert all letters to capital letters.
16
Exercise 6 Solution
• Write a python program that read a text file about_ethiopia.txt and
convert all letters to capital letters.
17
If you have any questions, write it on
a comment section of this video
18