Python 3home |
Introduction to Python
davidbpython.com
With these we can see whether a file is a plain file, or a directory.
import os # os ('operating system') module talks
# to the os (for file access & more)
mydirectory = '/Users/david'
items = os.listdir(mydirectory)
for item in items:
item_path = os.path.join(mydirectory, item)
if os.path.isdir(item_path):
print(f"{item}: directory")
elif os.path.isfile(item_path):
print(f"{item}: file")
# photos: directory
# backups: directory
# college_letter.docx: file
# notes.txt: file
# finances.xlsx: file
This function tests to see if a file exists on the filesystem.
import os
fn = input('please enter a file or directory name: ')
if not os.path.exists(fn):
print('item does not exist')
elif os.path.isfile(fn):
print('item is a file')
elif os.path.isdir(fn):
print('item is a directory')
os.path.getsize() takes a filename and returns the size of the file in bytes
import os # os ('operating system') module
# talks to the os (for file access & more)
mydirectory = '/Users/david'
items = os.listdir(mydirectory)
for item in items:
item_path = os.path.join(mydirectory, item)
item_size = os.path.getsize(item_path)
print(f"{item_path}: {item_size} bytes")
moving and renaming a file are essentailly the same thing
import os
filename = 'file1.txt'
new_filename = 'newname.txt'
os.rename(filename, new_filename)
import os
filename = 'file1.txt' # or could be a filepath incluing directory
move_to_dir = 'old/'
os.rename(filename, os.path.join(move_to_dir, filename)) # file1.txt, old/file1.txt
import shutil
filename = 'file1.txt'
backup_filename = 'file1.txt_bk' # must be a filepath, including filename
shutil.copyfile(filename, backup_filename)
import shutil
filename = 'file1.txt'
target_dir = 'backup' # can be a filepath or just a directory name
shutil.copy(filename, target_dir) # dst can be a folder; use shutil.copy2()
This function is named after the unix utility mkdir.
import os
os.mkdir('newdir')
If your directory has files, shutil.rmtree must be used.
import os
import shutil
os.mkdir('newdir')
wfh = open('newdir/newfile.txt', 'w') # creating a file in the dir
wfh.write('some data')
wfh.close()
os.rmdir('newdir') # OSError: [Errno 66] Directory not empty: 'newdir'
shutil.rmtree('newdir') # success
import shutil
shutil.copytree('olddir', 'newdir')
Regardless of what files and folders are in the directory to be copied, all files and folders (and indeed all folders and files within) will be copied to the new name or location.