0

I have txt-file in the form:

1 2 3 4 5 6
7 8 9 10 11 
12 13 14 15 

So for me, the lines are obviously seperated by beginning a new line.

Now I want to read these lines and store every line to a new variable. I tried:

with open('centroids_ET.txt') as f:
      CD_cent=f.readlines()  

and also:

with open('centroids_ET.txt') as f:
     CD_cent = []
     for line in f:
           CD_cent.append(line)

But It always stores all other lines in this variable as well. I checked with print(len(line)) if it recognizes all lines, but it takes all as one line as it seems.

So my question, how can I fix this? Is it maybe an issue of the layout of the txt-file? Do I need to seperate the lines in the txt-file in a special way? Thanks in advance!

Leo
  • 113
  • 1
  • 4
  • 13
  • What will you do by storing every line to new variable? – Rahul Jul 11 '17 at 07:49
  • These approaches both store all the lines in a list - each entry of the list is a single line. Do you want to do something like line1 = '1 2 3 4 5 6', line2 = '7 8 9 10 11', etc? This will be much harder to work with than a list, and very tricky to do in a reasonable way if you don't know in advance how many lines are in your list. If you do know there are exactly three lines, you can just add ```line1, line2, line3 = CD_cent```. But keeping the lines in a list is probably better for whatever you're trying to do. – perigon Jul 11 '17 at 07:49
  • `[l.strip() for l in f.readlines]` gives `['1 2 3 4 5 6', '7 8 9 10 11', '12 13 14 15']`. – Oleksii Filonenko Jul 11 '17 at 07:55

3 Answers3

3

Now, having everything in a list should be everything you need from a doing what you need point of view - there is no real advantage to having everything in a separate variable unless it improves your code legibility/quality.

(You can always access the elements in CD_cent via indexes start at 0. e;g to get the 2'nd element you would use CD_cent[1])

However, if you knew the number of lines in your file you could always do this

with open("My_File") as f:
    #We know there are 3 lines
    #You may want to rstrip to remove newline characters
    line1 = f.readline()
    line2 = f.readline()
    line3 = f.readline()

Now if you don't, and I stress that this seems useless, you could always do this:

with open("MY_FILE") as f:
    #NUM_LINES can change
    #You may want to rstrip to remove newline characters
    for lineNum in range(1,NUM_LINES+1):
        exec("line"+str(lineNum)+" = f.readline()")

Now this would produce variables line1, line2 and line3 if NUM_LINES was 3, line1,line2,...,line5 if NUM_LINES was 5 ect.

Please note that this code is python 3.4, which is what I believe you are using

Marcus Handley
  • 182
  • 2
  • 10
1

Edit: Even easier and shorter https://stackoverflow.com/a/3277516/2019601

input.txt:

1 2 3 4 5 6
7 8 9 10 11 
12 13 14 15 

test.py:

with open("input.txt") as fh:
  content = fh.read()

lines = []
for line in content.split("\n"):
  lines.append(line)

print(lines) 

Output: (Three lines -> Three elements in the array)

['1 2 3 4 5 6', '7 8 9 10 11 ', '12 13 14 15 ']
keocra
  • 613
  • 5
  • 10
0

try this:

    def main():
    fname = "PythonQuestion.txt"
    with open(fname) as f:
        content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content]
    print content

if __name__ == '__main__':
    main()

This will result in an array with this content:

['1 2 3 4 5 6', '7 8 9 10 11', '12 13 14 15']