You can more conveniently move files, for example, from /home/tssfl/Desktop/Old_Folder/ to a new folder, /home/tssfl/Desktop/New_Folder/ on the Desktop by using the following piece of code:
- import glob
- import shutil
- filenames = sorted(glob.glob('/home/tssfl/Desktop/Old_Folder/*.h5'))
- filenames = filenames[:]
- for f in filenames:
- shutil.move(f, "/home/tssfl/Desktop/New_Folder/")
Note that, sorted function is not needed/necessary, it only rearranges files alphabetically.
You can as well use the mv command.
The mv command moves folders/files recursively and does not have an -r flag.
Use the -i option for being prompted in case a file with the same name exists if you do not want the file to be replaced:
mv -i /home/tssfl/Desktop/Old_Folder/*.h5 /home/tssfl/Desktop/New_Folder/
If moving folders, use:
sudo mv /home/tssfl/folder1 /home/tssfl/folder2/
"/" in the end means you're moving folder1 inside folder2.
You can also move and rename files/folders, for example move file1.pdf from folder1 to folder2 and rename it file2.pdf
- mv /home/tssfl/Desktop/folder1/file1.pdf /home/tssfl/Desktop/folder2/file2.pdf
Do Even More Magic!
Now we can do things more magically, suppose we have nested folders: folder1, folder2, folder3, ..., foldern, defined by paths /home/tssfl/Desktop/folder1, /home/tssfl/Desktop/folder2, /home/tssfl/Desktop/folder3, ..., /home/tssfl/Desktop/foldern. Suppose further, inside each of these folders you have a file and/or a folder named: file, folder.
The structure of each of your nested folders will then look like:
- /home/tssfl/Desktop/folderx/
- file
- folder
where x = 1, 2, 3, ...n.
You can then rename your folders and files: file_n1.ext , folder_n1, folder_n2, file_n2.ext, folder_n3, file_n3.ext, ..., file_nn.ext, folder_nn, and move all of them to a new directory "new_directory" by using the script below:
- import os
- for i in xrange(n):
- path = "/home/tssfl/Desktop/folder%s" % (i+1)
- for filename in os.listdir(path):
- filename_without_ext = os.path.splitext(filename)[0]
- extension = os.path.splitext(filename)[1]
- new_file_name = filename_without_ext+"_n%s" % (i+1)
- new_file_name_with_ext = new_file_name+extension
- print(new_file_name_with_ext)
- os.rename(os.path.join(path,filename),os.path.join("/home/tssfl/Desktop/new_folder",new_file_name_with_ext))
The script will take care of whatever extensions (.ext) for your files.