简体   繁体   中英

Getting paths of each file of a directory into an Array in python

Im trying to put into an array files[] the paths of each file from the Data folder but when I try to go into subfolders I want it to be able to go down to the end of the Data file, for example I can read files in a subfolder of the main folder Data which im trying to get a list of all the paths of each file into an array but it doesn't go deeper it does not access the subfolder of the subfolder of Data without writing a loop. Want I want is a loop which has infinit depth of view of files in the Data folder so I can get all the file paths.

For example this is what I get:

['Data/DataReader.py', 'Data/DataReader - Copy.py', 'Data/Dat/DataReader.py', 'Data/fge/er.txt']

This is what I want but it can still go into deeper folders:

['Data/DataReader.py', 'Data/DataReader - Copy.py', 'Data/Dat/DataReader.py', 'Data/fge/er.txt', 'Data/fge/Folder/dummy.png', 'Data/fge/Folder/AnotherFolder/data.dat']

This is my current path, what would i need to add or change?

import os
from os import walk

files = []
folders = []
for (dirname, dirpath, filename) in walk('Data'):
    folders.extend(dirpath)
    files.extend(filename)
    break

filecount = 0
for i in files:
    i = 'Data/' + i
    files[filecount] = i
    filecount += 1

foldercount = 0
for i in folders:
    i = 'Data/' + i
    folders[foldercount] = i
    foldercount += 1

subfolders = []
subf_files = []
for i in folders:
    for (dirname, dirpath, filename) in walk(i):
        subfolders.extend(dirpath)
        subf_files.extend(filename)
        break

    subf_files_count = 0
    for a in subf_files:
        a = i + '/'+a
        files = files
        files.append(a)
        print files
    subf_files = []

print files
print folders

Thanks a lot!

Don't understand what are your trying to do, especially why you break your walk after the first element:

import os

files = []
folders = []
for (path, dirnames, filenames) in os.walk('Data'):
    folders.extend(os.path.join(path, name) for name in dirnames)
    files.extend(os.path.join(path, name) for name in filenames)

print files
print folders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM