0

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.

1

6 Answers 6

3

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])
Sign up to request clarification or add additional context in comments.

3 Comments

Note, however, that the sum approach to list flattening has quadratic time complexity. You are also not stripping the spaces.
@schwobaseggl Added striping also.
You might want to qualify this with regard to closing resources and the restriction of its current form to Python2.
2

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)

3 Comments

Fixed it. It was supposed, that solving this error would be your homework :)
Why do you have two answers?
@RoadRunner my first answer was written with the assumption that hbakan wanted to read all data into a single list. This one is about loading data into a list of lists.
2

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']

1 Comment

This is the cleanest and most Pythonic approach!
2

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)))

Comments

1

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)

5 Comments

You should account for the lines as well.
It looks like so, but author of the question said: "I need to generate 30 elements array", and I've answered to that need :)
I don't think you get a full 30 if you split only on commas ;)
Thank you very much, I also want to write these elements as a multidimensional array, how should I split them?
@HüseyinBakan i've added answer for multidimensional array stackoverflow.com/a/47992330/2622523
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.