5

I just started to learn python, so I need some help.

I have closeparams.txt file, it has CSV structure:

3;700;3;10;1
6;300;3;20;1
9;500;2;10;5

I need read this file to 2 dimension array. a[i,j] where i - is row and j - is column

I searched but not found exactly samples. I will use this massive like this:

i=0
j=3
print a(i,j)

I suppose that display:

10

Or

i=2
j=1
print a(i,j)

I suppose that display:

500
3
  • 4
    what have you tried ? there are a lot of methods to load a csv file : csv module, numpy.genfromtxt, ... Commented Nov 14, 2012 at 15:30
  • there are also a lot of ways one could parse/interpret the example data you've provided? Commented Nov 14, 2012 at 15:31
  • I no problem with separated read and array working, but I stuck with working this two at at once. Commented Nov 14, 2012 at 15:34

3 Answers 3

4

I suggest to use numpy if you want to deal with arrays. In your case:

import numpy

a = numpy.loadtxt('apaga.txt', delimiter=';')

print a[0,3]

You didn't specify how important will the array construct be for you, but Numpy is very, very powerful for complex tasks, and can be very lean to perform smaller, quick'n'dirty tasks in a compact, fast and readable way.

Sign up to request clarification or add additional context in comments.

5 Comments

I have try something like this
import numpy a = numpy.loadtxt(filename='closeparams.txt', delimiter=';') print a[0,3]
Two possible causes: 1) you are using Python 3.x, if so then print(a[0,3]) should do; 2) you are putting everything in one line, if so then separate lines.
Yes, I use Python 3.1.1, I correct print(a[0,3]) but in shell - import numpy ImportError: No module named numpy
@RedSubmarine You have to install numpy first. An alternative solution would be to use the built-in csv module.
3
display_list = []

with open('closeparams.txt') as data_file:
   for line in data_file:
      display_list.append(line.strip().split(';'))

print(display_list[0][3]) # [i][j]

edit - python3 print()

2 Comments

change the print statement to a print function call; print()
or install numpy and try heltonbiker's solution
3

How about:

import csv
sheet = list(csv.reader(open(source_path)))
print sheet[0][0]

Just typecast the opened csv to a list!

1 Comment

Your post has shown up in the Low Quality Posts review queue. This is likely because you haven't provided any explanation. Your code is fairly clear, so I am going to mark this answer "Looks OK", but explained code has greater potential to be helpful.

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.