0

I had an assignment due that asked to read a file and display the top 10 lines of the file, or all of the lines if the file is less than 10 lines long. When I tried to run my code on my computer, it registered the file as having 0 lines (no matter what file I used) and displayed only a blank line as output. I would like to understand where I went wrong so I can avoid my mistake for the next assignment. Any style or other tips are also welcome.

Here is my code:

#Displays the top 10 lines in a file

import sys

# Make sure the input is correct, take file name
if len(sys.argv) == 2:
    filename = sys.argv[1]
else:
    print("You must start the program with 1 command line parameter.")
    quit()

# open file    
fle = open(filename, "r")

#Count number of lines
linecount = 0
for line in fle:
    linecount = linecount + 1

# If the file is less than 10 lines, print the entire file
# If the file has more than 10 lines, print only first 10.
lines = fle.readlines()
if linecount < 10:
    for line in fle:
        print(line,)        
else:
    for i in range(10):
        print(lines[i])

4 Answers4

3

Could it be that

for line in fle:
    linecount = linecount + 1

reads every line from the file so that, after the loop is done, there are no more lines to read from that file in lines = fle.readlines()?

Try inserting a fle.seek(0) before lines = fle.readlines() to "rewind" the file to the beginning before re-reading it.

(See also here for example.)

Community
  • 1
  • 1
JimmyB
  • 12,101
  • 2
  • 28
  • 44
  • I'm not quite sure I understand here. I tried printing the line count right after the 'for line in fle:' loop, and it was 0. The program isn't picking anything up when counting the lines. How would 'fle.seek(0)' before 'lines = fle.readlines()' help me? @_@ – Musicalducky Apr 11 '14 at 08:37
  • Hmm. In that case there must be another problem elsewhere. Wrong filename or non-existent/empty file maybe. However, if Lawrence's soulution works we don't need to dig any deeper :) – JimmyB Apr 11 '14 at 11:33
2

You don't need to count the lines, or to check for limits on the lines, Python can do all this for you. Just do it like this:

with open(filename, "r") as fle:
    lines = fle.readlines()
    print '\n'.join(lines[:10])

Update:

If you insist on using your own code, here is the fixed version:

#Displays the top 10 lines in a file

import sys

# Make sure the input is correct, take file name
if len(sys.argv) == 2:
    filename = sys.argv[1]
else:
    print("You must start the program with 1 command line parameter.")
    quit()

# open file    
fle = open(filename, "r")

lines = fle.readlines()
linecount = len(lines)

if linecount < 10:
    for line in lines:
        print(line)        
else:
    for i in range(10):
        print(lines[i])
bosnjak
  • 8,424
  • 2
  • 21
  • 47
  • Thank you! I don't think our prof taught us about ''\n'.join(lines[:10])' but it seems to make sense to me. Would you happen to know why my code didn't work by any chance? I know mine is kind of a mess but I still can't figure out why it isn't working.... – Musicalducky Apr 11 '14 at 08:31
  • You should replace your line `for line in fle:` with `for line in lines:`, because you just read the whole file, you don't need to read it again. The second one, after the `if linecount < 10:` – bosnjak Apr 11 '14 at 08:36
  • Mmmm that did _something_. Now it's just telling me there aren't enough lines in 'lines' for the final print statement. @_@ – Musicalducky Apr 11 '14 at 08:41
  • Remove the part that counts the lines altogether. You are moving your file pointer to the end there, and there is nothing more to read later. – bosnjak Apr 11 '14 at 08:44
  • Aiighty, makes sense. Now how do I handle the case later if a file has less than 10 lines without that? – Musicalducky Apr 11 '14 at 08:47
  • Here is your fixed code: http://pastie.org/9072376 but i suggest using the one from my answer anyway. – bosnjak Apr 11 '14 at 08:47
  • Thank you so much! Sadly they want us to use python the way they're teaching us, even if it's a complete train wreck. It just wouldn't do to fail the final because I used something I wasn't supposed to. I hope I will eventually be able to python freely. – Musicalducky Apr 11 '14 at 08:53
  • Possible duplicate of [Iterating on a file using Python](http://stackoverflow.com/questions/10255273/iterating-on-a-file-using-python). – JimmyB Apr 11 '14 at 11:35
1

I would write the code as below which is simple

with open("give_your_file_path") as file_to_read:
    head=[file_to_read.next() for x in xrange(10)]

Then,

print head

There you go, it prints whatever you needed.

Hope this helps you

kingmakerking
  • 2,017
  • 2
  • 28
  • 44
  • *The* pythonic solution ;) – smassey Apr 11 '14 at 08:25
  • Ooohhhh maaannn. Well this looks pretty, but I don't think we ever learned this in class. If I started whipping out pretty code the teachers would get suspicious. But thank you! – Musicalducky Apr 11 '14 at 08:27
  • @Musicalducky You can always claim that you have gained proficiency over time and practice and hence improvised ;) Lol.... – kingmakerking Apr 11 '14 at 08:30
  • @smassey Yes it is :) – kingmakerking Apr 11 '14 at 08:30
  • @sidnext2none would you happen to know by any chance why my code didn't work? I know it's a mess and looks ugly as heck, but I'm still trying to figure out why it wouldn't work. I should _definitely_ spend more time on this website it seems, what we're learning in class is a train wreck. – Musicalducky Apr 11 '14 at 08:34
0

if you want count the file lines in Unix platform:

import os
def linecount_wc(filePath):
    command = "wc -l %s" % filePath
    return int(os.popen(command).read().split()[0])
BlackMamba
  • 10,054
  • 7
  • 44
  • 67