read_folder

read_folder(
    path,
    pattern='\\.csv$',
    id='file',
    all_character=True,
    question_row=None,
    encoding='utf-8',
    **kwargs,
)

Read and stack every CSV in a folder.

Loads all CSV files matching pattern in path, reading each as text (so survey codes never get silently coerced), tags every row with its source filename, and stacks the lot into one data frame, so a folder of monthly or per-event exports becomes one dataset. Reading every column as text is deliberate, because survey exports are ragged (a column that is numeric in one file may carry “Prefer not to answer” in another), and stacking text columns never fails. Recode the types you need afterwards with the recode_*() helpers or ensure_numeric(). The id column records which file each row came from; split it into metadata with parse_filename().

Survey platforms commonly write the question wording as a second header row, which reads back as respondent number one and quietly skews every count by one. A file whose first row is long, spaced prose in most columns at once and numeric in none is reported as such; question_row=True drops that row from every file, and False keeps it without comment.

R takes a readr locale; the port takes the file encoding directly.

Parameters

Name Type Description Default
path str Directory to read from. required
pattern str Regular expression matching the files to load. Default all CSVs. '\\.csv$'
id str Name of the column in which to record each row’s source filename. Default “file”. None omits it. 'file'
all_character bool If True (default), every column is read as text, with surrounding whitespace trimmed and “” or “NA” read as missing, as readr does. If False, types are guessed per file. True
question_row bool What to do with a second header row of question wording. None (default) keeps it and warns when a file looks like it has one; True drops the first row of every file; False keeps it silently. None
encoding str File encoding. Default “utf-8”; pass “cp1252” for legacy Windows exports. 'utf-8'
**kwargs Passed to pandas.read_csv(). {}

Returns

Name Type Description
pandas.DataFrame All files stacked together. If columns differ across files, missing columns are filled with missing values.

See Also

select_prefix, parse_filename

Examples

>>> import tempfile, os
>>> folder = tempfile.mkdtemp()
>>> podracing_survey.head(3).to_csv(os.path.join(folder, "a.csv"), index=False)
>>> podracing_survey.head(2).to_csv(os.path.join(folder, "b.csv"), index=False)
>>> read_folder(folder)[["file", "respondent_id"]]