Skip to content Skip to sidebar Skip to footer

Linux Lines Counting Not Working With Python Code

I am using WC -l to count number of lines in a text document. However I got a problem here. I got a python code that wrote different combination of numbers into different files. ea

Solution 1:

The join you are using is placing newlines between lines, but not at the end of the last line. Hence, wc is not counting the last line (it counts the number of newlines).

Add output_file.write("\n") at the end of your script, in the with clause:

  with open(filename, 'w') as output_file:
     output_file.write("\n".join(combination_as_strings))
     output_file.write("\n")

Solution 2:

I think you are seeing a variant of this:

$ printf '1\n2\n3' | wc -l

at the Bash prompt type this -- prints 2 because there is no final \n

Compare to:

$ printf '1\n2\n3\n' | wc -l

which prints 3 because of the final \n.

Python file methods do not append a \n to their output. To fix you code, either use writelines like so:

with open(filename, 'w') as output_file:
    output_file.writelines(["\n".join(combination_as_strings),'\n'])

or print to the file:

with open(filename, 'w') as output_file:
     print >>output_file, "\n".join(combination_as_strings)

or use a format template:

with open(filename, 'w') as output_file:
     output_file.write("%s\n" % '\n'.join(combination_as_strings))

Solution 3:

Why not use writelines?

output_file.writelines(line+"\n" for line in combination_as_strings)

Solution 4:

The wc command counts the number of new line characters in the file (\n).

So if you have 10 lines on a file, it'll return 9, because you will have 9 new line characters.

You could make it work as you want by adding an empty new line at the end of each file.


Post a Comment for "Linux Lines Counting Not Working With Python Code"