1

I am trying to retrieve the number of lines of a file using python on ubuntu.

I tried the following:

os.system("wc -l fileName")

But it returns something like

numberOfLines fileName
0

When I tried to retrieve the result: l = os.system("wc -l fileName")

I got l = 0

I also tried to split the result in order to keep the first element only, but this raises AttributeError: 'int' object has no attribute 'split'

How can I get the number of lines I am looking for?

bigTree
  • 2,103
  • 6
  • 29
  • 45

1 Answers1

3

os.system will return the exit value of the wc -l command, which is zero if no error occurs.

You want the actual output of the program:

#TODO: handle CalledProcessError, malformatted output where appropriate

wc_output = subprocess.check_output(["wc", "-l", fileName])
num_lines = int(wc_output.split()[0])
w-m
  • 10,772
  • 1
  • 42
  • 49
  • 2
    It's worth knowing that `wc` prints the filename if it's an argument, but not if counting lines from stdin. – kojiro Mar 07 '14 at 14:32
  • @w.m Similarly, I tried subprocess.check_output(["ls","files*"]) but got an error telling the file files* doesn't exist. How can I specify that I want all the files whose name begins with files? – bigTree Mar 07 '14 at 14:43
  • @w.m er, not that my happiness has anything to do with it, but wouldn't it be better just to redirect the file to stdin for wc, rather than using split? – kojiro Mar 07 '14 at 14:45
  • @bigTree lookup glob/globbing and maybe the shell=True flag (and its security warnings) – w-m Mar 07 '14 at 15:07
  • @kojiro you'd have to open the file in Python or use shell=True though? – w-m Mar 07 '14 at 15:13
  • @w.m Depends how the script is run. You could always do the redirect before executing the script. But opening the file in Python would be a reasonable way. – kojiro Mar 07 '14 at 15:23
  • @kojiro Hm, ok. And with the shell thing I wasn't sure whether you meant check_output("wc -l < filename", shell=True), because that would work too, I guess. – w-m Mar 07 '14 at 15:31