برنامج تعليمي Python

تحويل ملف نصي إلى CSV في Python

تحويل ملفات النص إلى CSV في Python مع أمثلة قابلة للنسخ لوحدة csv المدمجة وpandas. معالجة الإدخال المفصول بتاب ومسافة ومخصص، والحفاظ على ترميز UTF-8، والتحكم في الاقتباس.

خطوة بخطوةCopy-paste codeFree converter included
إعلان
نظرة عامة

Two ways to convert text to CSV in Python

Python is ideal for repeatable text-to-CSV conversion. The standard library’s csv module is perfect for streaming a file line by line, while pandas is convenient when you also want to clean or reshape the data. Both are shown below with runnable code.

For a one-off conversion you do not need to write any code — the online converter handles it instantly — but a script wins when the job repeats or is part of a pipeline.

Using the csv module

The csv module reads and writes correctly quoted CSV without external dependencies. To convert a tab-separated text file to comma CSV:

Python — tab-delimited text to CSV
import csv

with open("input.txt", newline="", encoding="utf-8") as f_in:
    reader = csv.reader(f_in, delimiter="\t")   # input uses tabs
    rows = list(reader)

with open("output.csv", "w", newline="", encoding="utf-8") as f_out:
    writer = csv.writer(f_out)                  # default delimiter is a comma
    writer.writerows(rows)

If your text is separated by arbitrary whitespace (one or more spaces), split on whitespace instead of a fixed delimiter:

Python — whitespace-delimited text to CSV
import csv

with open("input.txt", encoding="utf-8") as f_in, \
     open("output.csv", "w", newline="", encoding="utf-8") as f_out:
    writer = csv.writer(f_out)
    for line in f_in:
        fields = line.split()          # split on any run of whitespace
        if fields:                     # skip blank lines
            writer.writerow(fields)

Using pandas

With pandas you can let it sniff the delimiter, then write CSV in one line:

Python — pandas, auto-detect the delimiter
import pandas as pd

# sep=None + engine="python" sniffs the delimiter automatically
df = pd.read_csv("input.txt", sep=None, engine="python")
df.to_csv("output.csv", index=False)

Or be explicit about the input delimiter and the output options:

Python — pandas, explicit delimiter and quoting
import csv
import pandas as pd

df = pd.read_csv("input.txt", sep="\t", encoding="utf-8")
df.to_csv(
    "output.csv",
    index=False,                 # do not write the row index
    quoting=csv.QUOTE_MINIMAL,   # quote only when needed
    encoding="utf-8",
)

See the dedicated pandas guide for read_csv parameters in depth.

Delimiters, quotes and encoding

Three settings cover almost every case:

  • Delimiter — pass delimiter (csv) or sep (pandas). Use "\t" for tabs, "|" for pipes, ";" for semicolons.
  • علامات الاقتباس — csv.QUOTE_MINIMAL quotes only when needed; csv.QUOTE_ALL quotes every field.
  • Encoding — always pass encoding="utf-8". Use encoding="utf-8-sig" when writing a file that Excel must open with a BOM.
Python — write a BOM so Excel reads UTF-8 correctly
df.to_csv("for_excel.csv", index=False, encoding="utf-8-sig")
Good to know

Common errors and how to avoid them

The most frequent Python CSV mistakes are easy to prevent. Forgetting newline="" when opening a file for the csv module causes blank lines between rows on Windows, because the module and the OS both add carriage returns — always pass it. A UnicodeDecodeError on read means the source is not UTF-8; try encoding="latin-1" or detect the encoding first. With pandas, numbers that should keep leading zeros are converted unless you read them as strings with dtype=str. And if pandas guesses the wrong delimiter, set sep explicitly rather than relying on the sniffer.

To verify the result, read your own output back: list(csv.reader(open('output.csv', newline='', encoding='utf-8')))[:3] shows the first parsed rows, confirming columns split as intended. Building a tiny round-trip test like this into a script catches delimiter and quoting regressions before they reach real data.

الأسئلة الشائعة

Convert Text File to CSV in Python — FAQ

How do I use the csv module to convert text to CSV?

Open the text file with csv.reader using the input delimiter, then write rows with csv.writer, whose default delimiter is a comma.

How do I write CSV with pandas?

Load with pd.read_csv (set sep or use sep=None to auto-detect), then call df.to_csv("output.csv", index=False).

How do I set the encoding?

Pass encoding="utf-8", or "utf-8-sig" when the file must open in Excel with a BOM.

How do I convert a tab-delimited file?

Use delimiter="\t" with the csv module or sep="\t" with pandas.