Convert TXT to CSV in R
How to convert a TXT file to CSV in R while keeping values, column names and encoding intact, with base R and readr options and the cases where plain text is the better choice.
Converting a text file to CSV in R is usually two steps: read the file into a data frame with the right parser, then write it back out with comma delimiters. The conversion is only useful if the CSV still means what the original text meant. That depends on correctly identifying the source layout and on choosing settings that do not quietly reinterpret your values. This review covers what the conversion changes, when it suits your purpose, and how to check the result before you share it.
Is converting TXT to CSV the right move?
Convert when the text file already holds a table: rows of records, separated by tabs, consistent whitespace, a delimiter such as a pipe or semicolon, or fixed-width columns. The main benefit is interoperability. CSV is widely accepted by spreadsheet software, databases and other analysis tools, and each value sits in an addressable column.
The decisive tradeoff is that the conversion goes through R's parser, and the parser makes decisions. It decides where fields end, which values count as missing, what type each column is, and how column names are cleaned. With default settings, some of those decisions can alter the data. If you cannot confirm the source layout, or the round-trip check described below fails, the conversion is not yet safe to rely on.
Keep the file as plain text in these cases:
- The content is prose, a log with free-form messages, or anything without a consistent record structure. Forcing it into columns adds commas and quotes without adding meaning.
- The downstream tool already reads the tab-delimited or fixed-width file directly, so conversion only adds a step that could introduce errors.
- The file is an archival or legal record where byte-for-byte fidelity matters more than convenience. In that case, keep the original and treat any CSV as a derived copy.
What the conversion actually changes
Renaming a file from .txt to .csv changes nothing inside it. A tab-delimited file with a .csv extension is still tab-delimited, and software expecting commas may load it as a single column. A real conversion rewrites the stored characters. Delimiters become commas, some fields gain surrounding double quotes, embedded double quotes are doubled, and line endings and text encoding are set by the writer.
"TXT" does not describe a single format, so start by opening the file and identifying its structure. Each layout needs a different reader:
| Source layout | Base R reader | readr reader |
| Tab-delimited with header | read.delim() | read_tsv() |
| Any single-character delimiter (pipe, semicolon) | read.table(sep = "|") or read.delim(sep = ";") | read_delim(delim = "|") |
| Columns separated by runs of spaces | read.table(header = TRUE) | read_table() |
| Fixed-width columns | read.fwf(widths = ...) | read_fwf() |
Some changes are intended, and others are side effects of default settings. Base R's readers and writers behave differently from readr's, so it helps to know which defaults matter.
- Type inference: values that look numeric are converted to numbers. Leading zeros in codes such as "00123" are lost, "1.50" can be written back as 1.5, and long identifiers may change form. Reading every column as character avoids this.
- Missing values: by default, the literal text NA is read as missing. In numeric columns, blank fields also become missing. On output, missing values are written as NA unless you change the na argument.
- Column names: base R readers apply check.names = TRUE by default, which replaces spaces and other characters that are not syntactically valid, so a header like "Order ID" becomes "Order.ID". Setting check.names = FALSE keeps the original names.
- Row names: write.csv() adds an unnamed first column of row numbers unless you set row.names = FALSE. readr's write_csv() does not write row names.
- Quotes and comments in the source: read.table() treats both double quotes and apostrophes as quote characters and treats # as the start of a comment by default. Either can truncate or merge fields in whitespace-separated text. read.delim() and read.csv() use only double quotes and turn comment handling off.
- Encoding: base R reads and writes in the session's native encoding unless you pass fileEncoding. readr reads and writes UTF-8 by default.
A conversion that preserves values
For a tab-delimited UTF-8 file with a header row, the base R pattern below reads every column as text, keeps the original column names, and disables NA detection. Then it writes a CSV without row names. Adjust the reader and sep argument to match your layout.
df <- read.delim("input.txt",
colClasses = "character",
check.names = FALSE,
na.strings = character(0),
fileEncoding = "UTF-8")
write.csv(df, "output.csv",
row.names = FALSE,
fileEncoding = "UTF-8")
The equivalent with readr:
library(readr)
df <- read_tsv("input.txt",
col_types = cols(.default = col_character()),
na = character())
write_csv(df, "output.csv")
Reading everything as character fits when the goal is a faithful format change. If you need typed columns for analysis in R, convert them deliberately after reading, so each type change is a decision you made. Some locales use commas as decimal separators. For those, base R's write.csv2() writes semicolon-separated files with comma decimals, but that output is a different dialect and not a standard comma-separated file.
Will the CSV stay readable and usable once shared?
A CSV is still plain text, so it can be opened in any text editor, searched, and edited by hand. Its usability after sharing depends mostly on how the receiving application interprets it.
- Spreadsheet applications: readr's documentation describes write_excel_csv() as adding a byte order mark so that Excel recognizes the file as UTF-8. Without one, non-ASCII characters may display incorrectly in Excel. Behavior varies by application, version and locale, so test with the program your recipients actually use.
- Automatic reformatting on open: spreadsheet programs may reinterpret values when they open a CSV, for example by dropping leading zeros or reading some codes as dates. Quoting values in the file does not reliably prevent this. Recipients may need to import the file with columns set to text, and this is outside R's control.
- Copy and paste: pasting CSV text into a spreadsheet does not always split it into columns, while tab-separated text often does. Behavior depends on the destination and has not been verified here for any specific application. If people will paste the data rather than open a file, a tab-delimited copy may serve them better.
- Accessibility: a screen reader reading the raw file reads commas and quotes as characters, which makes rows hard to follow. When the same data is opened as a table in a spreadsheet, assistive technology can usually navigate by cell, but support differs between products. No specific screen reader was tested for this article. For readers who need the content rather than the data, a short plain-text summary or a properly marked-up table is more accessible than either file.
Check the result before relying on it
One clean-looking preview does not show that every row survived. Read the CSV back with the same preserving settings and compare it with the original data frame:
check <- read.csv("output.csv",
colClasses = "character",
check.names = FALSE,
na.strings = character(0),
fileEncoding = "UTF-8")
identical(df, check)
all.equal(df, check)
identical() returning TRUE means the round trip kept every value and name. If it returns FALSE, all.equal() reports where the two differ. Also compare the row count with the number of records in the source. A row count lower than expected often means an unmatched quote character merged several lines into one field, or a comment character cut lines short.
Evidence gaps
This review draws on the documented behavior of base R and readr functions. It does not include benchmark measurements, tests on a specific dataset, or verified results for particular spreadsheet programs or assistive technologies. Function defaults can change between package versions, so check the help pages for the versions you have installed, such as ?read.table and ?write_csv. Then run the round-trip check on your own file.