Array of file paths

A forum for general discussion of the Python programming language.

Array of file paths

Postby dogdaynoon » Fri May 24, 2013 12:03 am

I have a directory that contains layers of files and folders:
I would like to put all of the file paths, including directories, into an array of strings.

here is my code:
Code: Select all
dir = "testDir"
file_array = []
for dirname, dirnames, filenames in os.walk(dir):
   for filename in filenames:
      file_path = os.path.join(dirname, filename)
      file_array.extend(file_path)
      print(file_array)

This code creates an array of single characters for all of the files.
IE...
file_array['t', 'e', 's', 't', 'D', 'i', 'r', '\\', 'f', 'i', 'l', 'e', 'n', 'a', 'm', 'e', '.', 't', 'x', 't']
what the heck is that all about
i just want this:
file_array = ["dir/filenaem.txt", "dir/filename2.txt", etc...]
does that make sense?
python 3 windows 7
dogdaynoon
 
Posts: 12
Joined: Thu May 23, 2013 11:56 pm

Re: Array of file paths

Postby metulburr » Fri May 24, 2013 12:25 am

the reason you are getting each char, is by using extend() method. Which concatenates to the list. You are giving the value of a string (Ie the path) to extend method.
Code: Select all
>>> l = []
>>> l.extend('path')
>>> l
['p', 'a', 't', 'h']


Either use append() method instead, or make it a tuple or list to extend to the list.
Code: Select all
>>> l = []
>>> l.extend(('path',))
>>> l
['path']

Code: Select all
>>> l = []
>>> l.append('test')
>>> l
['test']



I would like to put all of the file paths, including directories, into an array of strings.

you mean list, not array.
So you want just all subdirectories and files' full paths?

Code: Select all
import os

fullpaths = []
for (root, dirs, files) in os.walk("debian"):
    if files:
        for file in files:
            file_fullpath = os.path.abspath(os.path.join(root, file))
            fullpaths.append(file_fullpath)
    if dirs:
        for dir in dirs:
            dir_fullpath = os.path.abspath(os.path.join(root, dir))
            fullpaths.append(dir_fullpath)

for path in sorted(fullpaths):
    print(path)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1385
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Array of file paths

Postby dogdaynoon » Fri May 24, 2013 2:28 pm

You are a genius. I am super new to python and am struggling along.


some day i may figure out what everything means


Thank you!!!
dogdaynoon
 
Posts: 12
Joined: Thu May 23, 2013 11:56 pm


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 0 guests