hbakan
hbakan

Reputation: 17

How to write elements to the array in Python

I read elements from a txt file and I want to write elements to the array, I know I must use substring method but I don't know how to generate an array while I am using substring method.

example.txt file includes

001, A, 50, 70, 65
002, B, 25, 55, 80
003, C, 60, 40, 85
004, D, 75, 55, 70
005, E, 40, 40, 45
006, F, 35, 25, 85

My python code:

file = open("example.txt", "r")
a = file.read()
print(a)

I need to generate 30 elements multi dimensional(5x6) array, I can read elements of this file using this code but I wonder that how to write them to the array.

Upvotes: 0

Views: 286

Answers (6)

sgardner2011
sgardner2011

Reputation: 21

if you want to keep the formatting of the CSV file and have a two dimensional array then maybe setting up the 2d array first then iterating through the file and adding in the values might be the way to go.

array = []

for row in range(0,6):
    array.append([])
    for col in range(0,5):
        array[row].append(" ")

print(array)

Then to add your vales in instead of the spaces, import the file, iterate through each row and for each value add it to the corresponding space in your 2d array

Upvotes: 0

MihanEntalpo
MihanEntalpo

Reputation: 2072

To get multidimensional array you need to read file line by line, and split every line by commas, like in my previous answer

# Prepare result array:
array = []
# Open file
with open("example.txt", "r") as f:
    # read the contents of file line by line:
    for line in f:
        # split current line by comma to get array of items from it
        array_parts = line.split(",")
        # filter elements, removing empty, and stripping spaces:
        array_parts = [item.strip() for item in array_parts if item.strip() != ""]
        # add line's items into result array:
        array.append(array_parts)        
# Printing result:
print(array)

Upvotes: 2

Rahul K P
Rahul K P

Reputation: 16091

You can do like this, Using split

In [14]: print map(str.strip,sum([i.split(',') for i in open("example.txt").split('\n')],[]))
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85']

flattening list with different method,

result = map(str.strip,[item for sublist in [i.split(',') for i in txt.split('\n')] for item in sublist])

Upvotes: 3

user2390182
user2390182

Reputation: 73470

Lots of decent comprehension based solutions around. Here is one to use map and itertools.chain:

from itertools import chain
with open("example.txt", "r") as f:
    array = list(chain(*(map(str.strip, line.split()) for line in f)))

Upvotes: 2

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

All you need is str.split() along with str.strip() as:

with open("example.txt") as f:
    my_list = [w.strip() for l in f for w in l.split(',')]
#                ^ to remove extra white-spaces 

which will return you my_list list as:

>>> my_list
['001', 'A', '50', '70', '65', '002', 'B', '25', '55', '80', '003', 'C', '60', '40', '85', '004', 'D', '75', '55', '70', '005', 'E', '40', '40', '45', '006', 'F', '35', '25', '85']

Upvotes: 2

MihanEntalpo
MihanEntalpo

Reputation: 2072

You need to read the data as a string, and when split it by a comma and newline character:

# Open file
with open("example.txt", "r") as f:
    # read the contents and replace "\n" characters by commas
    thedata = f.read().replace("\n", ",")
    # split it by "," creating an array
    array = thedata.split(",")
    # if it's needed, remove empty elements and trim spaces:
    array = [item.strip() for item in array if item.strip() != ""]
# Printing result:
print(array)

Upvotes: 1

Related Questions