Printing lines from file using python returning value in column, not by row

1963 views python
-3

I must have forgotten basic python since I cannot seem to print out lines by actual lines after splitting them so that each line as its elements in a list.

For example:

for lines in open(testfile):
     print(lines.split())

Outputs (note this is not a list of lists):

 ["The", "apple", "banana", "check"]
 ["Two", "apples", "three", "checks", "testest"]
 ["This", "is", "a", "test", "file"]

So if I want to print the very first line by itself I change the code to:

for lines in open(testfile):
     print(lines.split()[0])

But I get the first element in each line list:

 "The"
 "Two"
 "This"

But I expected:

["The", "apple", "banana", "check"]

I know this is syntax error and I have looked it up but I keep getting the first element only. Sorry this is so basic, but it's been a while since I've had to do something simple like this!

answered question

2 Answers

8

Your for loop is going to look at each line in turn, so when you print(lines.split()[0]), you are doing that for a single line at a time. What you could do is put all of the split-up lines in a list of their own and then look at the first element in that list:

all_lines = []  # empty list
for line in open(testfile):
     all_lines.append(line.split())
all_lines[0]
# ["The", "apple", "banana", "check"]

posted this
7

You can simply break right after printing the first line:

for lines in open(testfile):
     print(lines.split())
     break

This will print only the first line

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories