Why URLs Imported from CSV Files Sometimes Fail

Find spaces, nonbreaking spaces, and BOMs in imported URLs. Inspect CSV values in a spreadsheet or Python and review hosts before opening links.

Published
Reading time
8 min read
Why URLs Imported from CSV Files Sometimes Fail
On this page

URLs from CSV files may look correct in a spreadsheet but fail after import because the cell contains extra spaces or invisible characters. The reverse can happen too: an importer may alter a value that was supposed to be preserved. This guide shows how to inspect suspicious values, make a reviewable cleanup, and check destination hosts before opening links.

Key Takeaways

  • Check for ordinary spaces, nonbreaking spaces, and byte-order marks at the start and end of each imported value.
  • Keep the original column. A cleaned value is a proposal to review, not proof that the URL is correct or safe.
  • Do not globally remove spaces or decode percent-encoded characters: path and query values may be meaningful.
  • Review the parsed hostname before opening a link. A plausible-looking URL is not necessarily a trusted destination.

Why URLs from CSV files stop working

A CSV field can contain characters that are hard to see in a cell. An importer might reject them, preserve them, or remove some of them. Behavior varies by application.

Consider these labeled examples. The labels in brackets describe characters; they are not part of the URLs.

Test caseValue as describedPossible effect
Leading space[SPACE]https://example.com/pathThe importer may reject the value or interpret it differently.
Trailing spacehttps://example.com/path[SPACE]A copied value may contain an unintended extra character.
Nonbreaking space[NBSP]https://example.com/pathIt looks like a space but may survive a cleanup that only targets ordinary spaces.
Byte-order mark[BOM]https://example.com/pathIf present inside a field, this invisible character may interfere with recognition.
Encoded query spacehttps://example.com/search?q=red%20shoes%20 is part of the URL text; do not remove it as if it were extra whitespace.

A byte-order mark can also appear at the beginning of a UTF-8 file, before the first header. If an importer treats it as part of that header, a column named url may not match the expected name. That is different from a BOM embedded in a URL field.

Advertisement

Inspect values in a spreadsheet

These examples use functions found in some spreadsheet products. Function names, separators, Unicode support, and CSV import behavior vary, so adapt them to your product. Keep a copy of the original file before importing or changing it.

Create labeled test cells

On a new sheet, enter a label in column B and the corresponding formula in column A:

CellFormulaLabel
A2=" "&"https://example.com/path"&" "Ordinary spaces at both ends
A3=UNICHAR(160)&"https://example.com/path"Leading nonbreaking space
A4=UNICHAR(65279)&"https://example.com/path"Leading BOM character
A5="https://example.com/search?q=red%20shoes"Encoded space in query; preserve it

These are cell-level tests. To investigate the real file, import a copy as text using the appropriate UTF-8 option for your spreadsheet, then inspect the imported URL column. An import wizard may already have changed the values, so compare with the original file using the programming check below if the behavior is unclear.

Check the boundary characters

For a nonempty value in A2, these formulas identify the first and last characters by Unicode code point:

=IF(LEN(A2)=0,"(empty)",UNICODE(LEFT(A2,1)))
=IF(LEN(A2)=0,"(empty)",UNICODE(RIGHT(A2,1)))

For these tests, 32 identifies an ordinary space, 160 a nonbreaking space, and 65279 a BOM character. A character at the boundary may be intentional, so inspect the context before removing it. These checks do not find hidden characters in the middle of a value.

Propose a limited cleanup

For a review column, the following formula removes at most one ordinary space, nonbreaking space, or BOM from the beginning of A2. It leaves the original cell unchanged:

=IF(LEN(A2)=0,A2,IF(OR(UNICODE(LEFT(A2,1))=32,UNICODE(LEFT(A2,1))=160,UNICODE(LEFT(A2,1))=65279),MID(A2,2,LEN(A2)),A2))

If that result is in C2, this formula removes at most one of the same characters from its end:

=IF(LEN(C2)=0,C2,IF(OR(UNICODE(RIGHT(C2,1))=32,UNICODE(RIGHT(C2,1))=160,UNICODE(RIGHT(C2,1))=65279),LEFT(C2,LEN(C2)-1),C2))

If several boundary characters are present, repeat the checks and cleanup in additional columns or use the script below. Compare the candidate with the original before exporting. In particular, do not use a global find-and-replace for spaces or nonbreaking spaces: it can alter a path or query value.

Advertisement

Inspect a CSV with Python

This example requires Python and a UTF-8 CSV with a column named url. It uses only the standard library. The script reads a BOM at the beginning of the file separately from characters inside fields, prints the original and proposed values, and flags suspicious candidates for review. It does not modify the file or open any links.

The example has not been executed in this environment; run it on a copy of your data and check the results before using it in a workflow.

Create a small test file

Save this as make_test_csv.py and run python make_test_csv.py. It creates url_test.csv in the current directory; use a different directory if a file with that name already exists.

import csv

rows = [
    ("ordinary spaces", " https://example.com/path "),
    ("nonbreaking space", "\u00a0https://example.com/path"),
    ("BOM inside field", "\ufeffhttps://example.com/path"),
    ("encoded query space", "https://example.com/search?q=red%20shoes"),
    ("internal space", "https://example.com/search?q=red shoes"),
]

with open("url_test.csv", "w", encoding="utf-8-sig", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["label", "url"])
    writer.writerows(rows)

The file also starts with a UTF-8 BOM. The utf-8-sig reader in the next script handles that file-level marker; the BOM inside the labeled URL field remains available for inspection.

Review the values and hosts

Save this as review_urls.py, then run python review_urls.py url_test.csv. For another file, provide its path instead. The script intentionally limits automatic cleanup to selected boundary characters. It flags internal whitespace, control and format characters, and backslashes instead of rewriting them.

import csv
import sys
import unicodedata
from urllib.parse import urlsplit

# Policy for proposed boundary cleanup, not a universal definition
# of characters that are safe to discard.
BOUNDARY_CHARS = " \t\r\n\u00a0\ufeff"


def inspect(candidate):
    if not candidate:
        return "REVIEW: empty value"

    for char in candidate:
        category = unicodedata.category(char)
        if char.isspace() or category in ("Cc", "Cf") or char == "\\":
            return "REVIEW: whitespace, control, format character, or backslash remains"

    try:
        parts = urlsplit(candidate)
        if parts.scheme.lower() not in ("http", "https"):
            return "REVIEW: expected an HTTP or HTTPS scheme"
        if not parts.netloc or not parts.hostname:
            return "REVIEW: missing hostname"
        if parts.username is not None or parts.password is not None:
            return "REVIEW: URL contains user information"
        port = parts.port  # Access also checks whether a supplied port is valid.
        host = parts.hostname
    except ValueError as error:
        return f"REVIEW: could not parse URL: {error}"

    return f"HOST FOR REVIEW: {ascii(host)}; port: {port!r}"


def main(path):
    with open(path, encoding="utf-8-sig", newline="") as file:
        reader = csv.DictReader(file)
        if not reader.fieldnames or "url" not in reader.fieldnames:
            raise ValueError("CSV must have a column named 'url'")

        for row_number, row in enumerate(reader, start=2):
            raw = row.get("url")
            if raw is None:
                print(f"Row {row_number}: REVIEW: missing URL field")
                continue

            candidate = raw.strip(BOUNDARY_CHARS)
            print(f"Row {row_number}")
            print(f"  Original:  {ascii(raw)}")
            print(f"  Candidate: {ascii(candidate)}")
            print(f"  Changed:   {candidate != raw}")
            print(f"  {inspect(candidate)}")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("Usage: python review_urls.py path/to/file.csv")
    try:
        main(sys.argv[1])
    except (OSError, UnicodeError, csv.Error, ValueError) as error:
        sys.exit(f"Could not review CSV: {error}")

ascii() makes non-ASCII characters visible as escape sequences in the report. The candidate retains %20 exactly as written. A literal internal space is flagged rather than automatically removed or encoded. This matters because changing a query such as q=red shoes to a different value can change the request; the intended correction depends on the source data.

The script is an inspection aid, not a complete URL validator or safety scanner. Its boundary policy can remove an intentional literal character at the end of a path or query. Review every changed row against the source and your importer's requirements before accepting it. If the file uses another encoding or CSV dialect, adjust the reader deliberately rather than ignoring decoding errors. Treat the report as potentially sensitive if URLs contain tokens or personal data.

  1. Work from a copy. Preserve the original URL and keep the proposed cleaned value in a separate column or report.
  2. Inspect the actual hostname. Compare it with an independently maintained list of expected destinations. Do not rely on a familiar word elsewhere in the URL: in https://trusted.example@other.example/path, the destination host is other.example, not trusted.example.
  3. Investigate unfamiliar or deceptive-looking names. Pay attention to spelling, subdomains, and internationalized characters. An HTTPS scheme alone does not establish that a destination is trustworthy.
  4. Check with the data owner when uncertain. Do not open suspicious links just to find out where they lead. Avoid sharing URLs containing credentials, tokens, or personal data with third-party tools.
  5. Approve and import deliberately. Once the source and destination are confirmed, apply the agreed cleanup and retain an audit trail of changed rows. Redirects can lead to a different destination, so an initial host check is not a guarantee about the final page.

Common Mistakes

  • Deleting every space in a column. This can change meaningful path or query data, rather than merely fixing an import artifact.
  • Treating %20 as an unwanted literal space. It is an encoded sequence in the URL text; preserve it unless a documented transformation is required.
  • Assuming a visible cell shows every character. Check boundary code points or inspect the original file with a script.
  • Confusing a file-level BOM with a character inside a field. The former can affect the first header; the latter can affect an individual value.
  • Assuming parsing proves safety. A parser can help identify a hostname, but it cannot establish that the destination is trustworthy.

Best Practices

Agree on the expected CSV encoding, column name, and permitted URL schemes with the data producer. Preserve originals, flag ambiguous values, and document any cleanup rules. Test the workflow with representative rows before processing the full list, especially if a downstream tool silently normalizes imported values.

Conclusion

When URLs from CSV files are not working, inspect the exact characters before changing them. A narrow, reviewable boundary cleanup can resolve accidental whitespace and BOMs while preserving meaningful URL text. Check destination hosts independently before opening or importing the results.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.