Here are three ways to read a text file into the list in Python:
- Using readlines()
- Using file.read() with string.split()
- Using numpy.loadtxt()
Here is an apple.txt file that we will use for this article.
Ensure the text file (apple.txt) is in the same directory as your Python script, or provide the full path to the file.
Method 1: Using readlines()
This is a straightforward method that reads all lines in a file and returns a list where each line is an element in the list.
# Open the file in read-only mode
with open('apple.txt', 'r') as file:
# Read lines into a list
company_list = file.readlines()
# Remove newline characters from each element
company_list = [company.strip() for company in company_list]
# Now `company_list` is a list where each element is a company name from the file
print(company_list)
Output
['apple, microsoft, amazon, alphabet, facebook']
Method 2: Using file.read() with string.split()
This method first reads the entire file content into a single string using file.read(). Then, it splits the string into a list of lines using string.split().
This can be helpful for more complex splitting criteria.
# Open the file in read-only mode
with open('apple.txt', 'r') as file:
# Read the entire file content into a single string
file_content = file.read()
# Split the string into a list at each newline
company_list = file_content.split('\n')
# Remove empty strings if any (in case there are blank lines in the file)
company_list = [company.strip() for company in company_list if company]
# Now `company_list` is a list where each element is a company name from the file
print(company_list)
Output
['apple', 'microsoft', 'amazon', 'alphabet', 'facebook']
Method 3: Using numpy.loadtxt()
This method is great for reading files with numerical data into an array or list.
This method expects the file to have structured data. If your file contains non-numeric data or irregular structure, this method might not be appropriate.
import numpy as np
# Load the file into an array of strings
company_list = np.loadtxt('apple.txt', dtype=str, comments=None)
# Now `company_list` is a NumPy array where each
# element is a company name from the file
print(company_list)
Output
['apple' 'microsoft' 'amazon' 'alphabet' 'facebook']
Conclusion
If you are dealing with a standard text file and just want to read its lines, readlines() is the simplest choice.
If you need more control over the splitting, file.read().split() is more flexible.
For numerical or structured data, use the numpy.loadtxt() method.
Coolhappyasad
Thanks a lot this really help