python - Create directories based on filenames -


I am making a complete start to programming, so I apologize if it is really original I have other questions Have seen that which are related, but this particular problem has not been solved - at least it is not what I can understand.

I need to prepare a list of files; Create a separate directory for each file containing the directory name based on the name of each file; And put each file in its related directory.

You should keep an eye on the libraries.

I wrote an example for you that it will remove the file extension of each file in a given folder, create a new subdirectory, and move the file to the related folder, ie .:

  c: \ test \ - & gt; Test1.txt - & gt; Test2.txt   

will be

  c: \ test \ - & gt; Test1 \ - & gt; Test1.txt - & gt; Test2 \ - & gt; test2.txt   

code:

  import glob, os, shutil folder = 'c: test / file_path / In 'Glob.glob (os.path.join (folder,' *. * ')): New_dir = file_path.rsplit ('. ', 1) [0] os.mkdir (os.path.join (folder, new_dir )) Shutil.move (file_path, os.path.join (new_dir, os.path.basename (file_path)))   

The folder already exists if it will throw an error to avoid it To control the exception: For file_path in glob.glob

  import glob, os, shutil folder = 'C: / test /' (os.path.join (folder, ' *. * ')): New_dir = file_path.rsplit ('. ', 1) [0] Try: OSMADDir (OS path.join (fol Fear, new_dir)) handles except WindowsError: # case where there are already existing targets diapers. Passil.move (file_path, os.path.join (new_dir, os.path.basename (file_path)))   

PS: it will not work for files without extensions such cases Consider using a more robust code for.

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -