Home » Python » python – How can I import a series of text files into a dataframe, with each file as one input, not separated by deliminators?-Exceptionshub

python – How can I import a series of text files into a dataframe, with each file as one input, not separated by deliminators?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I would like to import a series of text files into a dataframe, with the filename as a column and the text string in the second column.

For instance, I have two text files and I would like the result to be as shown below.

enter image description here

I’ve tried the code block below, but I am getting an error that ‘str’ object has no attribute ‘name’. Is there a better way to do this? Thanks!

files = ['TXT1.txt', 'TXT2.txt']
from collections import defaultdict
results = defaultdict(list)
for f in files:
with open(f,"r") as file_open:
    results["file_name"] = file.name
    results["text"].append(file_open.read())
transcriptsDF = pd.DataFrame(results)
How to&Answers:

You have a typo in your code.

file.name should be file_open.name