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

1963 views python

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):

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):

But I get the first element in each line list:


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


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):
# ["The", "apple", "banana", "check"]

posted this

You can simply break right after printing the first line:

for lines in open(testfile):

This will print only the first line

posted this

Have an answer?


Please login first before posting an answer.