Home  >  Article  >  Backend Development  >  How to Parse Text Files into Lists or Arrays with Python?

How to Parse Text Files into Lists or Arrays with Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 15:28:02137browse

How to Parse Text Files into Lists or Arrays with Python?

Utilizing Python to Parse Text Files into Lists or Arrays

When working with text files in Python, one common task is to parse their lines into lists or arrays. This allows you to individually access each item for further processing.

Consider a text file with data formatted as follows:

<code class="text">0,0,200,0,53,1,0,255,...,0</code>

To read this file into a list, we can use the readlines() method:

<code class="python">text_file = open("filename.dat", "r")
lines = text_file.readlines()</code>

However, the output reveals that the entire file is stored as a single list item, not a list of individual values. This is because the file is read as a single string.

To overcome this, we need to split the string into separate values using the split() method:

<code class="python">lines = text_file.read().split(',')</code>

This will split the string based on the comma (,) delimiter and store the resulting values in the lines list.

Alternatively, for more complex text files, we can use the csv module to read data:

<code class="python">import csv
with open('filename.csv', 'r') as fd:
    reader = csv.reader(fd)
    for row in reader:
        # Process each row here</code>

This approach will automatically parse each row into a list, providing an idiomatic way to work with CSV files.

The above is the detailed content of How to Parse Text Files into Lists or Arrays with Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn