Use Python’s collections.Counter when you want to know which lines in a text file appear more than once and how often each one appears. Read the file line by line, remove the line ending, and count the resulting text. Start with an explicit rule about spaces and case. It is much easier to trust a duplicate report when you know what the program treated as the same line.
Start with equality you can explain
Suppose you exported a text file with one tag per line. You want to know whether the same tag appears twice so you can fix a report later. The first decision is whether Ready and ready belong to the same group. The second is whether spaces around a tag matter. These choices depend on the data source. User-facing tags may be intentionally case-insensitive, while a code, identifier, or fixed-width record may use every character.
The example preserves case and spaces. It ignores physically empty lines and removes the line ending so a final line without a newline can still match a terminated line. A line containing one space is a different value under this rule. That might feel strict for tags, but it gives you a clear baseline before you add any cleanup.
This article treats each physical line as a record. If the input is CSV and can contain quoted line breaks, start with the Python CSV guide and count fields or rows after parsing. Otherwise, one CSV record can become multiple unrelated lines in the report.
Make a small fixture with intentional differences
Save the following as tags.txt. Keep the uppercase R in the third line. It gives you a visible example of a value that looks related but is distinct under the default rule.
ready
hold
Ready
ready
hold
Save the following as count_lines.py in the same folder. The command-line argument names the file to read. Relative paths follow the terminal’s current folder, so this sample command assumes you are in the folder containing the fixture.
import argparse
from collections import Counter
from pathlib import Path
parser = argparse.ArgumentParser(description="Count repeated nonempty text lines.")
parser.add_argument("file", type=Path)
args = parser.parse_args()
try:
with args.file.open(encoding="utf-8-sig", newline=None) as source:
counts = Counter()
for raw_line in source:
line = raw_line.removesuffix("\n")
if line:
counts[line] += 1
except (OSError, UnicodeError) as error:
parser.exit(2, f"Could not read {args.file}: {error}\n")
found = False
for line, count in counts.most_common():
if count < 2:
break
print(f"{count:>4} {line!r}")
found = True
if not found:
print("No repeated nonempty lines.")
Run python count_lines.py tags.txt. You should get the following output. A line with count two appeared twice in the file. If you plan to remove copies later, that means it has one extra occurrence beyond the first.

2 'ready'
2 'hold'
Follow the pieces of the script
The file opens as text. The newline=None setting translates common input line endings to a newline as Python reads them. Removing only that final newline keeps any spaces that are part of the line. The encoding choice here is for UTF-8 text and accepts an initial UTF-8 signature if an exporter supplied one. It does not infer arbitrary file encodings. If your input comes from an older tool, identify its export encoding first. Python text I/O documentation
A Counter holds a key for each distinct text value it has seen and a count for that key. The loop reads each line once. You do not need to build a second list containing every line before counting. The dictionary still grows with the number of distinct values, so a file where nearly everything differs can use much more memory than an equally large file full of repeats. Python Counter documentation
The call to most_common() puts higher counts first. For equal counts, Counter keeps the order in which it first encountered the keys. That is why ready comes before hold in this fixture. If you later need alphabetical ordering for tied counts, sort the report explicitly by decreasing count and then by the text. Record that decision if another tool compares one run with the next.
Make whitespace and case choices visible
Keep spaces while you investigate them
Using !r prints a representation that shows quotes and makes some whitespace visible. Add a line that starts with a space before ready. It does not increase the count of the ordinary tag. Add the same spaced line again, and the report gives it its own row. This quick check tells you whether unexpected spaces in the original export could be splitting counts.
If your data contract says surrounding spaces are incidental, call strip() on the line before checking whether it is empty. That changes the meaning of a line containing only whitespace, which now becomes empty and is excluded. Run the old and new rules on a copy before adopting the change. A fixed-width export or a formatted document can use leading spaces to communicate something meaningful.
Fold case if the records are meant to ignore it
For case-insensitive text, use line.casefold() before counting. Run the fixture again and the ready group should grow from two to three. Case folding can merge more than simple ASCII uppercase and lowercase pairs. Decide whether the wider behaviour fits the record type. If the report needs to preserve how people originally typed each label, keep the first representative spelling separately and print it alongside the folded key.

Avoid applying every possible cleanup once you see a strange value. Two operations can each change the count, so change one rule at a time. Start with a few representative input lines, including one that should remain distinct. See what the tool reports before you run it on a larger export.
Know whether you need counts or locations
A count is useful for ranking common repeats. It cannot tell a colleague which line to fix. If you need the first location as well, enumerate the file from one and keep the first line number for each key. That gives you a short location hint without storing all occurrences. If every occurrence matters, store a list of positions per value and account for the extra memory.
A report for human cleanup can be different from a machine-readable export. Console representations are useful for spotting odd spacing. A structured report should have separate fields for text and count, and use a CSV or JSON writer to handle escaping. Decide before piping this display into another tool. A printed string can include quotes or backslashes that mean something to the representation but are not part of the underlying value.
Troubleshoot a result that surprises you
If every count is one, start with a copy of two lines that look identical. Look at their representation, or check how many characters each contains. Invisible spacing, a tab between words, a change of case, or a different punctuation character can make an apparent duplicate distinct. A later decision to normalise those differences should come from your data contract.
If the program reports that it could not read the file, check the name and current directory first. Quote a path with spaces when passing it through the shell. Then read the error to see whether you have an access issue or a decoding problem. Keep the report separate from the raw file. This script only reads its input, which makes it useful as a first step before anyone proposes removing rows.
For a large log file, consider whether repeated whole lines answer the actual question. A timestamp or request identifier can make every line different even when the same error text recurs. If the input has a known log structure, parse that structure and count a specific field. Taking the same number of characters off every line can corrupt the result when formats vary.
Check what the duplicate count means before acting
If a report shows three occurrences of one tag and two of another, it identifies two repeated values. The total number of extra occurrences is three: two beyond the first for the first tag, and one beyond the first for the second. Those questions often get mixed up in cleanup work. Label the number that matters before sending it to someone who was not involved in the first run.
If the file will be edited, keep a copy and decide which occurrence survives. You might want the first spelling, the most recent entry, or an occurrence associated with a particular record. A Counter intentionally drops that context. Add any useful location or record identifiers to a separate review before changing the input.
Try a fixture that separates line endings from spaces
Make a second file with one line ending after the first tag and no line ending after its final repetition. Add one blank line in between. This is a useful test because the default routine should count the two copies together and skip the empty line. It also confirms that the last record matters even if the editor did not put a final newline after it. If your editor adds the newline on save every time, compare the displayed result with the intentional fixture supplied alongside this article.

Then add a line containing a single space. That line is nonempty and will be counted under the default rule. When two such lines occur, the printed representation gives you a separate entry. If this seems strange for your input, take it as evidence that the normalisation rule needs a decision. An input of one label per line and an input consisting of text where layout is meaningful should be treated differently.
Keep just the largest counts when the report grows
For a report read on screen, the full descending list can get long. If you only want the most frequent ten keys, pass ten to most_common. Keep the threshold check if you only want genuine repeats, since some entries among the top ten may still have count one. If the workflow needs every repeated key, keep the full iteration and save the results to a file designed for reading or sorting afterward.
For very large exports with many distinct entries, the number of unique keys still determines the size of the Counter. A top-ten display does not remove the keys already collected. Consider a database grouping or an external sort if the complete set cannot fit in memory. Test the simple approach with enough realistic data to see whether this is a real constraint before making the workflow more complicated.
Keep your original fixture and a note of the equality rule. When somebody asks why two lines ended up in different groups, you can repeat the small example and show how case and spaces are handled. That makes the count a result others can verify.
