2

This question is how to get list of files from a directory into text file using python.

Result in the text file should exactly be like this:

E:\AA\a.jpg
E:\AA\b.jpg
...

How to correct the code below:

WD = "E:\\AA"
import glob
files = glob.glob ('*.jpg')
with open ('infiles.txt', 'w') as in_files:
    in_files.write(files +'\n')

4 Answers 4

2

glob.glob() returns a list. You have to iterate through it.

WD = "E:\\AA"
import glob
files = glob.glob ('*.jpg')
with open ('infiles.txt', 'w') as in_files:
    for eachfile in files: in_files.write(eachfile+'\n')
Sign up to request clarification or add additional context in comments.

Comments

1
  • Input directory path : WD = "E://AA"
  • You can assign specific file extention that you needed eg: path = WD+'/*.jpg',
  • if you need all file list then give '' eg: path = WD+'/'

    import glob w_dir = WD + "/*.jpg" with open("infiles.txt","wb")as fp: for path in [filepath for filepath in glob.glob(w_dir)]: fp.write(path+"\n")

Comments

0

Without path, glob.glob returns list of filename (No directory part). To get full path you need to call os.path.abspath(filename) / os.path.realpath(filename) / os.path.join(WD, filename)

>>> glob.glob('*.png')
['gnome-html.png', 'gnome-windows.png', 'gnome-set-time.png', ...]
>>> os.path.abspath('gnome-html.png')
'/usr/share/pixmaps/gnome-html.png'

With path, glob.glob return list of filename with directory part.

>>> glob.glob('/usr/share/pixmaps/*.png')
['/usr/share/pixmaps/gnome-html.png', '/usr/share/pixmaps/gnome-windows.png', '/usr/share/pixmaps/gnome-set-time.png',  ...]

import glob
import os

WD = r'E:\AA'
files = glob.glob(os.path.join(WD, '*.jpg'))
with open('infiles.txt', 'w') as in_files:
    in_files.writelines(fn + '\n' for fn in files)

or

import glob
import os

WD = r'E:\AA'
os.chdir(WD)
files = glob.glob('*.jpg')
with open('infiles.txt', 'w') as in_files:
    in_files.writelines(os.path.join(WD, fn) + '\n' for fn in files)

Comments

0

Here is a two line simple solution:

import os
filee = open('all_names.txt','w')
given_dir = 'the_dierctory'
[filee.write(os.path.join(os.path.dirname(os.path.abspath(__file__)),given_dir,i)+'\n') for i in os.listdir(given_dir)]

where given_dir is the directory name. The output is a text file (all_names.txt) where each line in the file is the full path to all files and directories in the given_dir.

1 Comment

how can be to list all *.mp4 filenames from directory and subdirectory?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.