1

Is it possible to create variables based on the number of lines in a file?

For example, assuming the file will always have an even-number of lines. If the file has 4 lines I want to create 2 variables. var1 will contain the first 2 lines and var2 will contain the following 2 lines. If the file has 10 lines I want to create 5 variables. Again the first var will have the first 2 lines, and the next var will have the following 2 lines and so on...

Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
Oliver Robie
  • 698
  • 1
  • 9
  • 23

2 Answers2

0

It is almost always a bad idea to create variable names based on some programmatic value. Instead use a native data structure. In this case it sounds like a list is what you need.

Here is a way to loop through a file and collect pairs of lines into a list of lists.

var = []
last_line = None
for line in open('data.txt', 'rU'):
    if last_line:
        var.append([last_line, line.strip()])
        last_line = None
    else:
        last_line = line.strip()
if last_line:
    var.append([last_line])
print(var)

Results:

[['line1', 'line2'], ['line3', 'line4'], ['line5', 'line6']]
tripleee
  • 158,107
  • 27
  • 234
  • 292
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125
0
from itertools import islice
num_lines = sum(1 for line in open('lines.txt'))
with open("lines.txt", "r+") as f:
    len_of_lines = num_lines
    count_ = 0
    while count_ < len_of_lines:
        var = list(islice(f, 2))
        # something with var
        print(var)
        count_ += 2
   >>>['xascdascac\n', 'ascascanscnas\n']
      ['ascaslkckaslca\n', 'ascascacac\n']
      ['ascascaca\n', 'ascacascaca\n']
      ['ascascascac\n']
Pradam
  • 773
  • 7
  • 16