The Wayback Machine - https://web.archive.org/web/20240910052920/https://www.geeksforgeeks.org/python-program-to-read-file-word-by-word/
Open In App

Python program to read file word by word

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file word by word.

Read file word by word

In this article, we will look at how to read a text file and split it into single words using Python. Here are a few examples of reading a file word by word in Python for a better understanding.

Example 1:

Let’s suppose the text file looks like this – Text File read-word-by-word-pythonCode Explanation:

Open a file in read mode that contains a string then use a for loop to read each line from the text file again use for loop to read each word from the line split by ‘ ‘.Display each word from each line in the text file.

Python
# Python program to read 
# file word by word
 
# opening the text file
with open('GFG.txt','r') as file:
 
    # reading each line    
    for line in file:
 
        # reading each word        
        for word in line.split():
 
            # displaying the words           
            print(word) 

Output:

Geeks
4
geeks

Time Complexity: O(n), where n is the total number of words in the file.
Auxiliary Space: O(1), as the program is reading and displaying each word one by one without storing any additional data.

Example 2:

Let’s suppose the text file contains more than one line. Text file.python-read-word-by-wordCode Explanation: Open a file in read mode that contains a string then use a for loop to read each line from the text file again use for loop to read each word from the line split by ‘ ‘.Display each word from each line in the text file.

Python
# Python program to read 
# file word by word
 
# opening the text file
with open('GFG.txt','r') as file:
 
    # reading each line    
    for line in file:
 
        # reading each word        
        for word in line.split():
 
            # displaying the words           
            print(word) 

Output:

Geeks
4
Geeks
And
in
that
dream,
we
were
flying.

Time complexity: O(n), where n is the total number of words in the file.
Auxiliary space: O(1), as only a constant amount of extra space is used to store each word temporarily while printing it.

For more please read this article: Read and writing text file


Previous Article
Next Article

Similar Reads

Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
Python program to read character by character from a file
Python is a great language for file handling, and it provides built-in functions to make reading files easy with which we can read file character by character. In this article, we will cover a few examples of it. Example Input: GeeksOutput: G e e k sExplanation: Iterated through character by character from the input as shown in the output.Read a fi
2 min read
Python Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap"Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”
4 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
How to read from a file in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line
5 min read
Upload file and read its content in cherrypy python
CherryPy is a web framework of Python which provides a friendly interface to the HTTP protocol for Python developers. It is also called a web application library. It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time.
3 min read
Read List of Dictionaries from File in Python
A dictionary in Python is a collection where every value is mapped to a key. Since they are unordered and there is no constraint on the data type of values and keys stored in the dictionary, it is tricky to read dictionaries from files in Python. Read a List of Dictionary from Text Files in PythonUsing Pickle ModuleUsing read( ) MethodThe problem s
3 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.literal_eval() method : Function safer than the ev
2 min read
Read Properties File Using jproperties in Python
In this article, we are going to see how to read properties file in python using jproperties module. It is a Java Property file parser and writer for Python. For installation run this command into your terminal. pip install jproperties Various properties of this module: get() Method or Index-Based access to reading the values associated with the ke
2 min read
How to read a numerical data or file in Python with numpy?
Prerequisites: Numpy NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different formats of file : The data can be saved in a txt file wh
4 min read
Python - Read file from sibling directory
In this article, we will discuss the method to read files from the sibling directory in Python. First, create two folders in a root folder, and one folder will contain the python file and the other will contain the file which is to be read. Below is the dictionary tree: Directory Tree: root : | |__Sibling_1: | \__demo.py | |__Sibling_2: | \__file.t
3 min read
How to Read Text File Into List in Python?
In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variable called data. after that we replace the end of t
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Read File As String in Python
Python provides several ways to read the contents of a file as a string, allowing developers to handle text data with ease. In this article, we will explore four different approaches to achieve this task. Each approach has its advantages and uses cases, so let's delve into them one by one. Read File As String In PythonBelow are some of the approach
3 min read
Read Html File In Python Using Pandas
In Python, Pandas is a powerful library commonly used for data manipulation and analysis. While it's primarily used for working with structured data such as CSV files, Excel spreadsheets, and databases, it's also capable of reading HTML files and extracting tabular data from them. In this article, we'll explore how to read an HTML file in Python us
5 min read
Read a text file using Python Tkinter
Graphical User Interfaces (GUIs) are an essential aspect of modern software development, providing users with interactive and visually appealing applications. Python's Tkinter library is a robust tool for creating GUIs, and in this article, we will delve into the process of building a Tkinter application that reads and displays the content of a tex
3 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
How to read specific lines from a File in Python?
Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways
3 min read
Read a file without newlines in Python
When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file without newlines in Python. Read a file without newl
2 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Learning Ef
7 min read
Read JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
4 min read
Python program to capitalize the first letter of every word in the file
The following article contains programs to read a file and capitalize the first letter of every word in the file and print it as output. To capitalize the first letter we will use different methods using Python. The Python String Method is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the
3 min read
Read a zipped file as a Pandas DataFrame
In this article, we will try to find out how can we read data from a zip file using a panda data frame. Why we need a zip file? People use related groups of files together and to make files compact, so they are easier and faster to share via the web. Zip files are ideal for archiving since they save storage space. And, they are also useful for secu
2 min read
How to read a CSV file to a Dataframe with custom delimiter in Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. pandas package is one of them and makes importing and analyzing data so much easier.Here, we will discuss how to load a csv file into a Dataframe. It is done using a pandas.read_csv() method. We have to import pandas library to use th
3 min read
How to read csv file with Pandas without header?
Prerequisites: Pandas A header of the CSV file is an array of values assigned to each of the columns. It acts as a row header for the data. This article discusses how we can read a csv file without header using pandas. To do this header attribute should be set to None while reading the file. Syntax: read_csv("file name", header=None) ApproachImport
1 min read
Read Text file into PySpark Dataframe
In this article, we are going to see how to read text files in PySpark Dataframe. There are three ways to read text files into PySpark DataFrame. Using spark.read.text()Using spark.read.csv()Using spark.read.format().load() Using these we can read a single text file, multiple files, and all files from a directory into Spark DataFrame and Dataset. T
3 min read
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Read File Without Saving in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article we will discuss how can we Read files without Saving them in Flask, we will also veri
2 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Flask and Pandas libraries along with the openpyxl d
3 min read
Python Program to Get the File Name From the File Path
In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path.  Better to have knowledge of: Python OS-modulePython path moduleRegular expressionsBuilt in rsplit()Method 1: Python OS-moduleExam
6 min read