DanielHolden
DanielHolden

Reputation: 599

How to create a list from filenames in a user specified directory in Python?

I want to create a new list in Python from filenames in a user defined directory .

I can't quite get my head around the subprocess syntax from the wiki and some of the commands using PIPE seem to be discouraged.

So I'd prompt to define which directory to load from:

directory = raw_input("Path to directory: ")

Then run subprocess.check_output(["ls", "*eg*.txt"]) in the specified directory and place the output into list1.

Upvotes: 2

Views: 11253

Answers (3)

nguaman
nguaman

Reputation: 971

#!/usr/bin/env python -u
# -*- coding: utf-8 -*-

from os import listdir
directory = raw_input("Path to directory: ")
files_dir =  listdir(directory)
newlist = []
for names in files_dir:
    if names.endswith(".txt"):
        newlist.append(names)
print newlist

Upvotes: 2

m.wasowski
m.wasowski

Reputation: 6387

You can just use function from standard library that does just what you want:

import os
list1 = os.listdir(directory)
print(list1)

Upvotes: 5

elzell
elzell

Reputation: 2306

You could do:

import os
import glob

files = list(glob.glob(os.path.join(directory,'*.*')))

Upvotes: 5

Related Questions