Files have a name and a path. The root folder is the lowest folder. It's c:\
on Windows and /
on Linux and Mac.
In a file path, the folders and filenames are separated by backslash \
on Windows and forward slash /
on Mac & Linux
print('c:\\spam\\eggs.png')
print(r'c:\spam\eggs.png')
You can use the join()
string method but it's for Windows only. An better alternative is to use the os
module
'\\'.join(['folder1', 'folder2', 'folder3', 'file.png'])
Use the os.path.join()
to combine folders with the correct slash
import os
os.path.join('folder1', 'folder2', 'folder3', 'file.png')
os.sep
os.getcwd()
will return the current work directory. The current working directory is the folder that any relative paths are relative to.
os.getcwd()
os.chdir()
will change the directory
os.chdir('c:\\')
os.getcwd()
Absolute paths begin with the root folder e.g. 'c:\\folder1\\folder2\\spam.png'
. Relative paths do not begins with the root folder e.g. 'folder1\\folder2\\spam.png'
The .
folder represents this (current) folder. The ..
folder represents the parent folder
os.path.abspath()
returns an absolute path from the path passed to it
os.path.abspath('spam.png')
os.path.abspath('..\\..\\spam.png')
os.path.isabs()
returns True
if the path passed to it is absolute
os.path.isabs('..\\..\\spam.png')
os.path.isabs('c:\\folder\\spam.png')
os.path.relpath()
return the relative path between two paths passed to it
os.path.relpath('c:\\folder1\\folder2\\spam.png', 'c:\\folder1')
os.path.dirname('c:\\folder1\\folder2\\spam.png')
os.path.basename('c:\\folder1\\folder2\\spam.png')
os.path.basename('c:\\folder1\\folder2')
os.path.exists()
returns True
if the filename passed to it exists
os.path.exists('c:\\folder1\\folder2\\spam.png')
os.path.exists('c:\\windows')
os.path.isfile('c:\\windows\\system32\\calc.exe')
os.path.isfile('c:\\windows\\system32')
os.path.isdir('c:\\windows\\system32\\calc.exe')
os.path.isdir('c:\\windows\\system32')
os.path.getsize()
returns a file's size
os.path.getsize('c:\\windows\\system32\\calc.exe')
os.listdir()
returns a list of strings of filenames
os.listdir('c:\\Users\\Public\\Music')
totalSize = 0
for filename in os.listdir('z:\\it'):
if not os.path.isfile(os.path.join('z:\\it', filename)):
continue
totalSize = totalSize + os.path.getsize(os.path.join('z:\\it', filename))
totalSize
os.makedirs()
can make folders
# os.makedirs('z:\\temp')
open()
will return a file object which has reading and writing-related methods.
Passing r
(or nothing) to open()
will open the file in read mode, w
for write mode, a
for append mode. Opening a non-exist filename in write or append mode will create that file.
helloFile = open('Z:\\IT\\Python\\General Python\\Snippets\\hello.txt')
helloFile.close()
helloFile = open('Z:\\IT\\Python\\General Python\\Snippets\\hello2.txt', 'w')
helloFile.close()
helloFile = open('Z:\\IT\\Python\\General Python\\Snippets\\hello.txt', 'a')
Call read()
to read the contents of a file
# helloFile.read()
# content = helloFile.read()
# print(content)
helloFile.close()
Call readlines()
to return a list of strings of the file's content
helloFile = open('Z:\\IT\\Python\\General Python\\Snippets\\hello.txt')
helloFile.readlines()
Call write()
to write contents (strings) to a file
# helloFile.write('Hello!!!')
helloFile.close()
import shelve
shelfFile = shelve.open('Z:\\IT\\Python\\General Python\\Snippets\\mydata')
shelfFile['cats'] = ['Zophie', 'Pooka', 'Simon', 'Fat-tail', 'Cleo']
#shelfFile.close()
# shelfFile = shelve.open('mydata')
shelfFile['cats']
shelfFile.keys()
list(shelfFile.keys())
list(shelfFile.values())
shelfFile.close()
import shutil
# shutil.copy('c:\\spam.txt', 'c:\\delicious')
# 'c:\\delicious\\spam.txt'
# shutil.copy('c:\\spam.txt', 'c:\\delicious\\spamspam.txt')
# 'c:\\delicious\\spamspam.txt'
Use shutil.copytree()
to copy a folder and all its contents
# shutil.copytree('c:\\folder', 'c:\\folder_backup')
# 'c:\\folder_backup'
Use shutil.move()
to move a file but also rename it as well
# shutil.move('c:\\spam.txt', 'c:\\delicious')
# 'c:\\delicious\\spam.txt'
# shutil.move('c:\\spam.txt', 'c:\\delicious\\eggs.txt')
# 'c:\\delicious\\eggs.txt'
import os
# os.unlink('bacon.txt')
Use os.rmdir()
to delete a folder (but the folder must be empty)
# os.rmdir('folder1')
Use shutil.rmtree()
to delete a folder and its entire contents
# shutil.rmtree('c:\\delicious')
Deleting can be dangerous, so do a dry run first i.e. commenting all deletion related commands and use print
to see the effect first
import os
os.chdir('Z:\\IT\\Python\\General Python\\test')
for filename in os.listdir():
if filename.endswith('.txt'):
#os.unlink(filename)
print(filename)
To install send2trash Module:
Win+R
to open "Run Dialog"cmd
, press Enter
pip install send2trash
Use send2trash.send2trash
to send file or folder to the recycling bin
import send2trash
# send2trash.send2trash('c:\\users\\al\\desktop\\file1.txt')
import os
for folderName, subfolders, filenames in os.walk('Z:\\IT\\Python\\General Python\\test'):
print('The folder is ' + folderName)
print('The subfolders in ' + folderName + ' are:' + str(subfolders))
print('The filenames in ' + folderName + ' are:' + str(filenames))
for subfolder in subfolders:
if 'New' in subfolder:
# os.rmdir(subfolder)
print('directory name: ' + str(subfolder))
for file in filenames:
if file.endswith('.txt'):
# shutil.copy(os.path.join(folderName, file), os.path.join(folderName, file + '.backup'))
print('file name:' + os.path.join(folderName, file))