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?

2

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

7 Comments

It's worth knowing that wc prints the filename if it's an argument, but not if counting lines from stdin.
@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?
@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?
@bigTree lookup glob/globbing and maybe the shell=True flag (and its security warnings)
@kojiro you'd have to open the file in Python or use shell=True though?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.