Reading a Text File into a List or Array in Python
When working with Python, reading a text file into a list or array is a common task. By doing so, you can easily access individual items within the collection.
However, a common issue arises when the entire file is being read as a single list item, preventing individual element access. To address this, you need to split the file into smaller components using the split() method.
Consider the following example:
<code class="python">text_file = open("filename.dat", "r") lines = text_file.read().split(',') print(lines)</code>
In this code, the read() method reads the entire file into a string. The split(',') method then splits the string using the comma as a delimiter, creating a list of individual items.
However, for larger files or more complex data structures, a more idiomatic approach is recommended:
<code class="python">import csv with open('filename.csv', 'r') as fd: reader = csv.reader(fd) for row in reader: # Perform operations on individual row items</code>
Using csv.reader() allows you to iterate over the file line by line as a list, providing a more efficient and convenient way to work with large text files.
The above is the detailed content of How to Read a Text File into a List or Array in Python: Single Element vs. Individual Access?. For more information, please follow other related articles on the PHP Chinese website!