Question

Im new on Python, Im actually on a short course this week, but I have a very specific request and I dont know how to deal with it right now: I have many different txt files in a folder, when I use the following code I receive only the filename of two of the many files, why is this? regards!

import dircache
lista = dircache.listdir('C:\FDF')
i = 0
check = len(lista[0])
temp = []
count = len(lista)
while count != 0:
if len(lista[i]) != check:
    temp.append(lista[i- 1])
    check = len(lista[i])
else:
    i = i + 1
count = count - 1
print (temp)
Was it helpful?

Solution 2

If I've understood you correct, you would like to get all files?

Try it in this case:

import os

filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
    filesList = files
    break
print(filesList)

If need full path use:

import os.path

filesList = None
dir = 'C:\FDF'
for root, dirs, files in os.walk(dir):
    for file in files:
        filesList.append(os.path.join(root, file))
print(filesList)

OTHER TIPS

Maybe you can use the glob library: http://docs.python.org/2/library/glob.html

It seems that it works UNIX-like for listing files so maybe it can work with this?

import glob

directory = 'yourdirectory/'
filelist = glob.glob(directory+'*.txt')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top