0

I want to index all the USB files in a dictionary with the path to them and the name of the file. I know I'll have to use recursion to analyse all the nested folders. I'm just not sure how to list those files, and access the USB drive. I looked around and found how to write to a USB but not how to list all the files in it. Thanks in advance.

3
  • do you have the option of executing a command from a python script to see the files? You could use the subprocess module and have it run find . from the USB drive itself then write this list to a file. Let me know if you'd like details on that. Commented Apr 11, 2017 at 18:47
  • Yes I have that option. Could you write a answer explaining how to use the module to do that? Commented Apr 11, 2017 at 18:51
  • If you want to use python, you could also try using the glob package which allows for unix style glob expressions and can return an iterable. Commented Apr 11, 2017 at 18:56

2 Answers 2

1

Sure, you can use a script like this (filling in your own path to the USB):

import subprocess


def main():
    cmd = 'find /Path/To/Your/USB/Here'
    p = subprocess.Popen(cmd, shell=True)
    print p.communicate()[0]


if __name__ == '__main__':
    main()

Now to run this, e.g. in unix/mac:

$ python nameOfThisPythonScript.py  > somefile.txt

Then you should see the contents of the USB listed in somefile.txt.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using a Windows machine at the moment, and I can't test it, but would changing the cmd to cmd = 'touch file_list.txt && find /path/to/your/usb/here > file_list.txt do that directly inside of the code?
Yes you can do that.
0

You can use this script with your usb path

import os
f=open('path to the list file',"w")
for root, dirs, files in os.walk('path to usb'):
    for dir in dirs:
        for file in files:
            f.write(os.path.join(root, file) + '\n')
f.close()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.