Python Forum
all i want to do is count the lines in each file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
all i want to do is count the lines in each file
#8
(May-18-2021, 11:42 PM)Skaperen Wrote: if it's a strange encoding i don't care if this is accurate. this is operation on my edit log which has time of edit and a file path.
Can just ignore encoding errors,there is a parameter for this errors="ignore" or errors='replace'(will be ?).
So can do a version showing this can just copy my own code from this Thread and make a little change.
import os

def find_files(file_type, path):
    os.chdir(path)
    with os.scandir(path) as it:
        for entry in it:
            if entry.name.endswith(file_type) and entry.is_file():
                yield entry.name

def count_lines(files):
    for file in files:
        with open(file, encoding='utf-8', errors="ignore") as f:
            for line_nr, _ in enumerate(f, -1):
                pass
        yield file, line_nr + 1

if __name__ == '__main__':
    path = r'E:\div_code'
    file_type = '.txt'
    files = find_files(file_type, path)
    line_count = count_lines(files)
    print(list(line_count))
Output:
[('alice_in_wonderland.txt', 3599), ('test.txt', 1807), ('W2Testfile.txt', 1396)]
Compare with wc
λ wc -l *.txt
  1396 W2Testfile.txt
  3599 alice_in_wonderland.txt
  1807 test.txt
  6802 total
Reply


Messages In This Thread
RE: all i want to do is count the lines in each file - by snippsat - May-19-2021, 12:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Row Count and coloumn count Yegor123 4 1,468 Oct-18-2022, 03:52 AM
Last Post: Yegor123
  Delete multiple lines from txt file Lky 6 2,492 Jul-10-2022, 12:09 PM
Last Post: jefsummers
  failing to print not matched lines from second file tester_V 14 6,451 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Extracting Specific Lines from text file based on content. jokerfmj 8 3,253 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Importing a function from another file runs the old lines also dedesssse 6 2,713 Jul-06-2021, 07:04 PM
Last Post: deanhystad
  [Solved] Trying to read specific lines from a file Laplace12 7 3,725 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  Split Characters As Lines in File quest_ 3 2,634 Dec-28-2020, 09:31 AM
Last Post: quest_
  How to use the count function from an Excel file using Python? jpy 2 4,596 Dec-21-2020, 12:30 AM
Last Post: jpy
  Find lines from one file in another tester_V 8 3,563 Nov-15-2020, 03:29 AM
Last Post: tester_V
  get two characters, count and print from a .txt file Pleiades 9 3,591 Oct-05-2020, 09:22 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020