datapug
datapug

Reputation: 2441

Best way to import an entire .txt. file in a single pandas row

Is there a better way to import a txt file in a single pandas row than the solution below?

import pandas as pd
with open(path_txt_file) as f:
    text = f.read().replace("\n", "")
df = pd.DataFrame([text], columns = ["text"])

Sample lines from the .txt file:

Today is a beautiful day.
I will go swimming.

I tried pd.read_csv but it is returning multiple rows due to new lines.

Upvotes: 1

Views: 1301

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You can concatenate the lines with .str.cat() [pandas-doc]:

text = pd.read_csv(path_txt_file, sep='\n', header=None)[0].str.cat()
df = pd.DataFrame([text], columns=['text'])

Upvotes: 2

Related Questions