Flash Gordon
Flash Gordon

Reputation: 21

Python3: Trying to read each file in a folder, and count how many \n are in each file

Long time searcher, first time caller. I'm trying to write some code for a co-worker to remove some of her tedious copy & pasting into excel to count the rows of each of her .txt files. I'm having some trouble getting my code to repeat correctly in Pycharm for every file after the first.

My task: Read each file within a folder and return a \n count for each file.

for files in os.listdir(".."):
    if files.endswith(".txt"):
        print(files)
        lines = -1
        try:
            f = open(files,"r")
            for line in files:
                lines += 1
        except:
            print("problem")
        print('%r has %r lines inside' % (files, lines))

So it's a little buggy. Layered for loops aren't my strong suit, but I cannot get it to return the next file count after the first file is read. Thanks.

Upvotes: 1

Views: 93

Answers (2)

dreamzboy
dreamzboy

Reputation: 841

Inside my testdir - /home/user/projects/python/test/ has the 2 files with contents.

test1.txt

a
b
c
d

test2.txt

e
f
g

Main Code

import os

testdir = '/home/user/projects/python/test'

for file in os.listdir (testdir):
    lc = 0     # line count - reset to zero for each file
    if file.endswith ('.txt'):
        filename = '%s/%s' % (testdir, file) # join 2 strings to get full path
        try:
            with open (filename) as f:
                for line in f:
                    lc += 1
        except:
            print ('Problem!')
    print ('%s has %s lines inside.' % (filename, lc))

Output

/home/user/projects/python/test/test1.txt has 4 lines inside.
/home/user/projects/python/test/test2.txt has 3 lines inside.

It is recommended to use with open () - no closing statement needed or manually use f.close () with each opened file. In another word, add f.close () after your line += 1 with the same indent as f.open ().

Perhaps it's more important to check whether the *.txt file exist than to check whether a file can be opened.

for file in os.listdir (testdir):
    lc = 0
    filename = '%s/%s' % (testdir, file)
    if file.endswith ('.txt') and os.path.isfile (filename):
        with open (filename) as f:
            for line in f:
                lc += 1
        print ('%s has %s lines inside.' % (filename, lc))
    else:
        print ('No such file - %s' % filename)

Upvotes: 1

user123567
user123567

Reputation: 13

I think this is what you want.

#!/usr/bin/python3
import os

def main():

    for files in os.listdir("PATH TO FOLDER CONTAINING THIS SCRIPT + TEXT FILES"):
        if files.endswith(".txt"):
            print(files)

            num_lines = sum(1 for line in open(files))

            print("problem")
            print('%r has %r lines inside' % (files, num_lines))

if __name__ == "__main__": main()

I just hunted around for some alternative ways to count the lines in files, and this is what I found. Please let us all know if it works or not.

Upvotes: 0

Related Questions