From 697558791bc45c04048c487c045d782b7ff9ece3 Mon Sep 17 00:00:00 2001 From: JS <44579963+Punisheroot@users.noreply.github.com> Date: Sat, 1 Aug 2026 17:11:17 +0200 Subject: [PATCH] [3.15] gh-110128: Ignore a truncated final row in csv.Sniffer --- Lib/csv.py | 6 +++++- Lib/test/test_csv.py | 16 ++++++++++++++++ ...026-07-31-20-00-00.gh-issue-110128.tRuNc8.rst | 2 ++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-07-31-20-00-00.gh-issue-110128.tRuNc8.rst diff --git a/Lib/csv.py b/Lib/csv.py index d666ae20bc7edf..166aa01d0e25b7 100644 --- a/Lib/csv.py +++ b/Lib/csv.py @@ -368,7 +368,11 @@ def _guess_delimiter(self, data, delimiters): """ from collections import Counter, defaultdict - data = list(filter(None, data.split('\n'))) + lines = data.split('\n') + if len(lines) > 1 and not data.endswith(('\r', '\n')): + # The sample may have been cut off in the middle of the last row. + lines.pop() + data = list(filter(None, lines)) # build frequency tables chunkLength = min(10, len(data)) diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py index 2ab529b51c207d..58147e22ee0e04 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -1563,6 +1563,22 @@ def test_zero_mode_tie_order_colon_first(self): with self.assertRaisesRegex(csv.Error, "Could not determine delimiter"): sniffer.sniff(sample) + def test_sniff_truncated_sample(self): + sniffer = csv.Sniffer() + # A single row without a line terminator is complete enough to sniff. + self.assertEqual(sniffer.sniff("a,b").delimiter, ",") + + # The last row may have been cut off in the middle of the sample. + for lineterminator in ("\n", "\r\n"): + with self.subTest(lineterminator=lineterminator): + sample = lineterminator.join(( + "a,b,c", + "d,e,f", + "g,h,i", + "j,k", + )) + self.assertEqual(sniffer.sniff(sample).delimiter, ",") + class NUL: def write(s, *args): diff --git a/Misc/NEWS.d/next/Library/2026-07-31-20-00-00.gh-issue-110128.tRuNc8.rst b/Misc/NEWS.d/next/Library/2026-07-31-20-00-00.gh-issue-110128.tRuNc8.rst new file mode 100644 index 00000000000000..b41e428331cd3a --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-31-20-00-00.gh-issue-110128.tRuNc8.rst @@ -0,0 +1,2 @@ +Fix :meth:`csv.Sniffer.sniff` failing to detect the delimiter when a sample +is truncated in the middle of its final row.