In this code example we show how to read a file word by word and display the contents
The process is as follows
Open a file in read mode which contains text.
Use a for loop to read each line from the text file.
Use another for loop to read each word from the line split by โ โ.
Display each word from each line in the text file.
Example 1
In this example we read in a text file called testfile.txt
The contents are as follows
this is a test file
# Read a file word by word # open the text file with open('testfile.txt','r') as file: # read each line for line in file: # read each word for word in line.split(): # display the words print(word)
This will display the following
>>> %Run readfile1.py this is a test file
Example 2
In this example we read in a text file called testfile2.txt which has more than one line of text
The contents are as follows
this is a test file
this is line 2
# Read a file word by word # open the text file with open('testfile2.txt','r') as file: # read each line for line in file: # read each word for word in line.split(): # display the words print(word)
This will display the following
>>> %Run readfile1.py this is a test file this is line 2
Link
This is in github
https://github.com/programmershelp/maxpython/tree/main/code%20example/file%20operations
readfile1 and the 2 text files called testfile and testfile2