Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
closed by

Do you all have short, monofunctional Python scraps that you use? 

I'll get going with a short scrap I use occasionally to tally sloc (source lines of code) in python projects:

# prints recursive count of lines of python source code from current directory

# includes an ignore_list. also prints total sloc

import os

cur_path = os.getcwd()

ignore_set = set(["__init__.py", "count_sourcelines.py"])

loclist = []

for pydir, _, pyfiles in os.walk(cur_path):

    for pyfile in pyfiles:

        if pyfile.endswith(".py") and pyfile not in ignore_set:

            totalpath = os.path.join(pydir, pyfile)

            loclist.append( ( len(open(totalpath, "r").read().splitlines()),

                               totalpath.split(cur_path)[1]) )

for linenumbercount, filename in loclist: 

    print "%05d lines in %s" % (linenumbercount, filename)

print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)

closed

4 Answers

0 votes
by (25.7k points)
selected by
 
Best answer
Here's a slightly modified version of the code you provided, utilizing Python 3 syntax and updated print statements:

import os

cur_path = os.getcwd()

ignore_set = {"__init__.py", "count_sourcelines.py"}

loclist = []

for pydir, _, pyfiles in os.walk(cur_path):

    for pyfile in pyfiles:

        if pyfile.endswith(".py") and pyfile not in ignore_set:

            totalpath = os.path.join(pydir, pyfile)

            with open(totalpath, "r") as file:

                linenumbercount = len(file.read().splitlines())

                loclist.append((linenumbercount, totalpath.split(cur_path)[1]))

for linenumbercount, filename in loclist:

    print("{:05d} lines in {}".format(linenumbercount, filename))

total_lines = sum([x[0] for x in loclist])

print("\nTotal: {} lines ({})".format(total_lines, cur_path))

This code should provide the same functionality as your original script but with minor adjustments to accommodate changes in Python syntax and the use of the print function.
0 votes
by (26.4k points)

Try to initialize a 2D list, check the below which helps you to initialize a list:

lst = [0] * 3

But,this wont work for a 2D list:

lst = [0] * 3

The operator * copies its operands, and copied lists developed with [] highlight a similar list. The right method to do this is:

>>> lst_2d = [[0] * 3 for i in xrange(3)]

>>> lst_2d

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> lst_2d[0][0] = 5

>>> lst_2d

[[5, 0, 0], [0, 0, 0], [0, 0, 0]]

Interested to learn the concepts of Python in detail? Come and join the python course to gain more knowledge in Python

Watch this video tutorial for more information...

0 votes
by (15.4k points)
import os

current_directory = os.getcwd()

ignore_list = ["__init__.py", "count_sourcelines.py"]

lines_of_code = []

for directory_path, _, file_names in os.walk(current_directory):

    for file_name in file_names:

        if file_name.endswith(".py") and file_name not in ignore_list:

            file_path = os.path.join(directory_path, file_name)

            with open(file_path, "r") as file:

                line_count = len(file.read().splitlines())

                lines_of_code.append((line_count, file_path.split(current_directory)[1]))

for line_count, file_path in lines_of_code:

    print("{:05d} lines in {}".format(line_count, file_path))

total_lines = sum([count for count, _ in lines_of_code])

print("\nTotal: {} lines ({})".format(total_lines, current_directory))

This version maintains the functionality of your original script while incorporating updates for Python 3 syntax and utilizing the print function with formatted string syntax.
0 votes
by (19k points)
import os

cur_path = os.getcwd()

ignore_set = {"__init__.py", "count_sourcelines.py"}

loclist = [(len(open(os.path.join(pydir, pyfile), "r").read().splitlines()), os.path.join(pydir, pyfile).split(cur_path)[1])

           for pydir, _, pyfiles in os.walk(cur_path)

           for pyfile in pyfiles

           if pyfile.endswith(".py") and pyfile not in ignore_set]

for linenumbercount, filename in loclist:

    print(f"{linenumbercount:05d} lines in {filename}")

print(f"\nTotal: {sum(x[0] for x in loclist)} lines ({cur_path})")

This condensed version achieves the same functionality as your original code while minimizing the number of lines and simplifying the structure by utilizing list comprehensions and formatted string literals (f-strings).

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
4 answers
0 votes
1 answer
asked Oct 29, 2019 in Python by humble gumble (19.4k points)

Browse Categories

...