2026년 11월 24일 화요일

Why a UTF-16 CSV retry can report “No columns to parse from file”

The retry can be reading from the end of the uploaded stream. A failed UTF-8 parse may already have consumed its bytes; changing the retry to UTF-16 does not reset the position. Check the position after the failure, then return a seekable stream to its start before retrying. This diagnosis applies when the upload remains open, supports seeking, and actually contains CSV data in the chosen encoding.

Why a UTF-16 CSV retry can report “No columns to parse from file”
A reading map of the checks explained below.

What does the error mean in this retry?

pandas.read_csv accepts a file-like object and an explicit encoding. The encoding tells pandas how to interpret bytes it reads; it does not make an earlier read available again. If the first attempt leaves the upload at its end, the second attempt receives no CSV header or data, even when UTF-16 is the correct encoding.

Treat the initial UnicodeDecodeError and the later empty-data error as observations from two separate attempts. The first points to a decoding problem with the selected UTF-8 attempt. The second may reflect where the next read began. Neither error alone proves that the upload has zero bytes.

Sources: pandas.read_csv — pandas.read_csv — Parameters: filepath_or_buffer; encoding, io — Core tools for working with streams — I/O base classes — IOBase.seek; IOBase.tell

How can I distinguish the causes?

After catching the UTF-8 decoding error, inspect upload.tell() if the stream supports it. That reports its current position. Compare it with the known byte length when available. A position at the end makes an unrewound retry a useful control: it tests the remaining bytes, which may be none, rather than testing whether UTF-16 can parse the original upload.

The recorded synthetic fixture used the same CSV content encoded once as UTF-8 and once as UTF-16. With pandas 2.0.3 on Python 3.9.6, the UTF-8 case parsed directly. In the UTF-16 case, the failed UTF-8 read left the BytesIO position at 32 of 32 bytes; an immediate UTF-16 retry raised EmptyDataError. This is a local result for that fixture, not a guarantee of how every upload object or pandas version positions its stream.

Sources: io — Core tools for working with streams — I/O base classes — IOBase.tell; IOBase.seekable, pandas.read_csv — pandas.read_csv — Parameters: encoding

How should the retry read the upload?

For a seekable upload, call upload.seek(0) after the failed attempt and before pd.read_csv(upload, encoding="utf-16"). Python documents zero as the start position for a seekable stream. In the recorded fixture, that rewind let the UTF-16 case parse the expected item and quantity row.

If the upload is not seekable, obtain a fresh readable stream from the original bytes before another attempt. Confirm that the stream is open and that the encoding matches the file being supplied. A successful rewind only restores access to bytes; it cannot fix an incorrect encoding or a file without parseable CSV columns. The fixture did not test framework upload wrappers, arbitrary encoding detection, or delimiter detection, so check those separately if a rewind still fails.

Sources: io — Core tools for working with streams — I/O base classes — IOBase.seek; IOBase.seekable; IOBase.close, pandas.read_csv — pandas.read_csv — Parameters: filepath_or_buffer; encoding; sep; header

Primary sources checked: 2026-11-24. Only the explicitly recorded fixture was tested locally; other guidance is documentation-based. No performance benchmark was performed.

Reproduce the locally verified result

pandas-csv-retry-stream-v1

Recorded environment: 3.9.6 / Darwin. Checked: 2026-11-24T12:49:26.528837+00:00

import io
import pandas as pd

print("pandas", pd.__version__)
for encoding in ("utf-8", "utf-16"):
    data = "item,qty\npen,2\n".encode(encoding)
    upload = io.BytesIO(data)
    try:
        rows = pd.read_csv(upload, encoding="utf-8")
    except UnicodeDecodeError:
        print(encoding, "after failed UTF-8 read:", upload.tell(), "of", len(data))
        try:
            pd.read_csv(upload, encoding="utf-16")
        except pd.errors.EmptyDataError:
            print("retry at current position: EmptyDataError")
        upload.seek(0)
        rows = pd.read_csv(upload, encoding="utf-16")
    print(encoding, rows.to_dict("records"))

Observed output

pandas 2.0.3
utf-8 [{'item': 'pen', 'qty': 2}]
utf-16 after failed UTF-8 read: 32 of 32
retry at current position: EmptyDataError
utf-16 [{'item': 'pen', 'qty': 2}]

One seekable synthetic BytesIO stream with a known encoding and comma delimiter per case. No Django upload, Teams export, arbitrary encoding detection or delimiter detection was tested.

2026년 11월 10일 화요일

Where did 00123 lose its zeros: pandas input, CSV export, or Excel import?

Check the identifier in the DataFrame, then in the CSV as plain text, then in Excel’s import preview. The first place 00123 becomes 123 tells you which step to fix. A value already reduced to 123 does not reveal how many zeros it originally had. This is a documentation-based comparison; no pandas or Excel run was recorded.

Where did 00123 lose its zeros: pandas input, CSV export, or Excel import?
A reading map of the checks explained below.

If the DataFrame already contains 123, fix the input

Inspect the value in the exact DataFrame passed to export. If the source CSV contains 00123 but the DataFrame contains 123, read the identifier column as text: pd.read_csv("input.csv", dtype={"code": str}). Check the resulting value before exporting. pandas documents per-column dtype selection and says column types can otherwise be inferred. This remedy applies to a nonmissing identifier: recognized missing values can still be parsed as missing despite the requested dtype.

If the DataFrame was assembled from an integer or another source that had already lost the zeros, changing read_csv or to_csv cannot recover the original spelling. Return to the original record. A known fixed width may support a display convention, but do not infer an unknown identifier from 123.

Sources: pandas.read_csv — pandas.read_csv — dtype

If the DataFrame has 00123, inspect the CSV itself

Open the exported CSV in a plain text editor before opening it in Excel. For the illustrative identifier, the expected CSV text is the following two literal lines, with the first line as the header: code 00123 This is an expected comparison point, not tested output. You may also inspect df.to_csv(index=False) for the DataFrame being exported; pandas documents that to_csv returns CSV text when no output path is supplied. Compare the same record in that text and in the saved file.

Use this reading map to choose the next action. It is a diagnostic comparison, not an experimental result. If the DataFrame contains 00123 but the raw CSV says 123, check that the object exported is the object you inspected and look for changes between inspection and export. If the raw CSV still says 00123, preserve that original file for a fresh Excel import.

If the DataFrame has 00123, inspect the CSV itself
First place 00123 becomes 123Likely step to investigateAction
DataFrame; source CSV still has 00123pandas inputRead the nonmissing identifier column as text and inspect it again
Raw CSV; exported DataFrame had 00123Export path or intervening changeConfirm the exported object and inspect the actual saved CSV
Excel; raw CSV still has 00123Excel conversion on importRestart import from the original CSV and retain the column as Text

Sources: pandas.read_csv — pandas.read_csv — dtype, pandas.DataFrame.to_csv — pandas.DataFrame.to_csv — Returns, Keeping leading zeros and large numbers — Keeping leading zeros and large numbers — Set automatic data conversions

If only Excel shows 123, protect the original text during import

Excel can convert numerical text to a number and remove leading zeros. Start from the original CSV that still contains 00123. In Excel, use Data > From Text/CSV and examine the import preview before loading. Verify that the original digits remain in the import data. Microsoft documents opening the editor and setting the identifier column’s data type to Text before Close & Load. If the preview or an earlier import step has already reduced the value to 123, restart from the original CSV; selecting Text after conversion cannot restore the missing digits.

Microsoft also describes Automatic Data Conversions controls for Excel for Microsoft 365 and Excel 2024, including their Mac editions. Availability depends on version. A custom number format can display a known width, but Microsoft says it does not restore zeros removed before formatting. For identifiers with unknown original width, recover the original text rather than applying a guessed format.

Sources: Keeping leading zeros and large numbers — Keeping leading zeros and large numbers — Convert numbers to text when you import text data, Keeping leading zeros and large numbers — Keeping leading zeros and large numbers — Set automatic data conversions, Keeping leading zeros and large numbers — Keeping leading zeros and large numbers — Use a custom format to keep the leading zeros

Primary sources checked: 2026-11-10. Prepared with AI assistance and a separate evidence review. This is documentation-based guidance, not a hands-on test or performance benchmark.