4

I have searched and cannot find the answer to this even though I am sure it is already out there. I am very new to python but I have done this kind of stuff before in other languages, I am reading in line form a data file and I want to store each line of data in it's own tuple to be accessed outside the for loop.

tup(i) = inLine

where inLine is the line from the file and tup(i) is the tuple it's stored in. i increases as the loop goes round. I can then print any line using something similar to

print tup(100)  
paisanco
  • 4,098
  • 6
  • 27
  • 33
cathyboo
  • 41
  • 1
  • 2

2 Answers2

3

Creating a tuple as you describe in a loop isn't a great choice, as they are immutable.

This means that every time you added a new line to your tuple, you're really creating a new tuple with the same values as the old one, plus your new line. This is inefficient, and in general should be avoided.

If all you need is refer to the lines by index, you could use a list:

lines = []
for line in inFile:
    lines.append(line)

print lines[3]

If you REALLY need a tuple, you can cast it after you're done:

lines = tuple(lines)
dckrooney
  • 3,041
  • 3
  • 22
  • 28
1

Python File Object supports a method called file.readlines([sizehint]), which reads the entire file content and stores it as a list.

Alternatively, you can pass the file iterator object through tuple to create a tuple of lines and index it in the manner you want

#This will create a tuple of file lines
with open("yourfile") as fin:
    tup = tuple(fin)

#This is a straight forward way to create a list of file lines
with open("yourfile") as fin:
    tup = fin.readlines()
Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • In your second example, wouldn't `lis = list(fin)` be simpler? And more appropriately-named? :^) – DSM Mar 27 '13 at 18:40