here_we_go69
here_we_go69

Reputation: 11

Storing all information from a directory into one list

Hello I am trying to store my directory into one list. I am able to call the directory with this code:

import os
path = r'c:/users/blahblahblah'
listing= os.listing(path)
for infile in listing:
 print "current file is: "+infile";

This outputs the each file from the directory. I want to call each file in the directory and store the contents of each file into a list. All the files are csv.

Thus after that I am having trouble calling the contents of each of those files and storing them as a list. Been at it a bit. Frustrated to say the least.

(My end goal is to be able to store these files in a sqlite3 db (which means a dataframe and dict won't suffice...trust me I've tried that...) Every step regarding the sqlite3 seems good to go.

Upvotes: 1

Views: 45

Answers (1)

Kat
Kat

Reputation: 1654

Easiest:

file_contents_list = [open(filepath).read() for filepath in os.listdir(path)]

This isn't great practice because it technically leaves file handles open but it should be fine for your purposes.

Upvotes: 1

Related Questions