10 Organizing Files Flashcards
- What does shutill stand for?
- What is its structure?
- What data type can shutil use?
- shell utilities
- shutil.copy(source, destination)
shutil.copytree(… , …)
shutil.move(
shutil.remtree(path)
–> after destination it is optional to use
destination\newName.filetype - Both source and destination can be either strings or Path objects
How can copy you the file spam.txt to another folder:
- keeping its name
- changing the name to spam2.txt
- copy the whole folder (incl. subfolders & files)
Use the home path as your folder path
p = Path.home()
- shutil.copy(p/spam.txt, new/path)
- shutil.copy(p/spam.txt, new/path/spam2.txt)
- shutil.copytree((p/spam, new/path/spamBackup)
- How can you move:
C:\bacon.txt to C:\eggs? - What happens, if the folder eggs exists in the C:\ directory?
- Wat happens if the folder eggs does NOT exist?
- What happens if the file bacon.txt exists in the destination directory?
- shutil.move(‘C:\bacon.txt’, ‘C:\eggs’)
- Than bacon.txt is moved into C:\eggs
- Than bacon.txt will be renamed as eggs (without the .txt extension!)
- Than the existing file is overwritten
- > Therefore, always be careful with move!
How can you:
- Delete a single file
- Delete a folder empty of files/subflders
- Delete a folder that is not empty?
- Delete a single file
os. unlink(path) - Delete a folder empty of files/subflders
os. rmdir(path) - Delete a folder that is not empty?
shutil. rmtree(path)
- Write a program to delete all .txt files in a folder
- How could you pre-check which files are about to be deleted? For example, if you accidentally typed .rxt instead of .txt
> > > from pathlib import Path
import os, shutil
> > > for filename in Path.home().glob(‘*.rxt’):
»_space;>os.unlink(filename)
- Comment os.unlink and insert:
»_space;>print(filename)
What is a much better way for deleting files? What is the downside?
Using the send2trash module, to prevent premanent deletion
> > > import send2trash
send2trash.send2trash(‘spam.txt’)
Downside: Doesn´t free up disk space
How can you get to each file and subfolder of a folder easily? For example to rename them.
using the os.walk function, which always returns 3x values on each iteration, e.g.:
for folderName, subFolder, fileName in os.walk(path): print(folderName) for subfolders in subFolder: print(subfolders) for filenames in fileName: print(filenames)
The print functions can be replaced with any other custom code
Probably using os.path.join(sourcePath, filename) necessary