How to read a text file into a list or an array with Python

ghz 3months ago ⋅ 73 views

I am trying to read the lines of a text file into a list or array in python. I just need to be able to individually access any item in the list or array after it is created.

The text file is formatted as follows:

0,0,200,0,53,1,0,255,...,0.

Where the ... is above, there actual text file has hundreds or thousands more items.

I'm using the following code to try to read the file into a list:

text_file = open("filename.dat", "r")
lines = text_file.readlines()
print lines
print len(lines)
text_file.close()

The output I get is:

['0,0,200,0,53,1,0,255,...,0.']
1

Apparently it is reading the entire file into a list of just one item, rather than a list of individual items. What am I doing wrong?

Answers

The issue you're encountering is that the entire content of your file is being read as a single string, since readlines() splits by newline characters (\n), and your file appears to contain a single line. Since the data in your file is comma-separated, you need to split the line on commas to get individual items.

Here's how you can modify your code to achieve this:

Updated Code:

# Open the file and read the content
with open("filename.dat", "r") as text_file:
    # Read the entire file content as a string and strip any extra whitespace or newlines
    content = text_file.read().strip()

# Split the string by commas to get individual items
data_list = content.split(',')

# Optional: Convert the items to integers (since they appear to be numbers)
data_list = [int(item) for item in data_list]

# Now you can access individual items in the list
print(data_list)  # To see the full list
print(len(data_list))  # Number of items in the list
print(data_list[0])  # Access the first item
print(data_list[-1])  # Access the last item

Explanation:

  1. with open(..., "r"): This ensures the file is properly opened and closed automatically.
  2. text_file.read().strip(): Reads the entire file content as a string and removes any extra whitespace or newline characters at the start or end of the file.
  3. split(','): Splits the string into a list using commas as delimiters.
  4. [int(item) for item in data_list]: Optionally, converts each string in the list to an integer for easier manipulation if you're working with numbers.

Output:

If your file contains:

0,0,200,0,53,1,0,255,...,0

The output data_list will look like:

[0, 0, 200, 0, 53, 1, 0, 255, ..., 0]

Now you can access individual items in data_list by their index, and len(data_list) will give the correct number of items.