0

My program cannot find the path that it just made, the program is for sorting files in the download folder. If it finds a new type of file it should make a folder for that file type.

import os
FileList = os.listdir("/sdcard/Download/")
for File in FileList:
 #print File
 extension = ''.join(os.path.splitext(File)[1])
 ext = extension.strip('.')
 if os.path.exists("/mnt/external_sd/Download/" + ext):
 Data = open("/sdcard/Download/" + File, "r").read()
 file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)
 elif os.path.exists("/mnt/external_sd/Download/" + ext) != True:
 os.makedirs("/mnt/external_sd/Download/" + ext)
 Data = open("/sdcard/Download/" + File, "r").read()
 file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data)
asked Aug 18, 2013 at 8:42
4
  • I haven't fooled around in Python for a while, but doesn't this line os.makedirs("/mnt/external_sd/Download/" + ext) create a directory, and not a file, which you then try to open? Commented Aug 18, 2013 at 8:44
  • @charmlessCoin: Well, he does then append "/" + File to it. Commented Aug 18, 2013 at 8:47
  • @charmlessCoin yes it does make a directory. Commented Aug 18, 2013 at 8:48
  • @DavidRobinson Whoops, just noticed that. Now I see what he's doing. Commented Aug 18, 2013 at 8:48

1 Answer 1

3

You create the directory

"/mnt/external_sd/Download/" + ext

but then you are trying to write to

"/mnt/external_sd/" + ext + "/" + File

You dropped the Download folder in that path. Change the last line to:

file("/mnt/external_sd/Download/" + ext + "/" + File, "w").write(Data)

Incidentally, it would be a bit shorter and clearer to write your last seven lines by taking the shared lines out of the if else statement and using shutil.copy instead of reading in the whole file then writing it out again:

import shutil
if not os.path.exists("/mnt/external_sd/Download/" + ext):
 os.makedirs("/mnt/external_sd/Download/" + ext)
shutil.copy("/sdcard/Download/" + File, "/mnt/external_sd/Download/" + ext + "/" + File)

(Using shutil will also generally be faster and use less memory, especially if your files are large).

answered Aug 18, 2013 at 8:48
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for finding that small but somewhat obvious mistake.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.