1.Filenames and Absolute/Relative paths:
'c:\\spam\\eggs.png'
'c:\\spam\\eggs.png'
print('\\')
\
r'c:\spam\eggs.png'
'c:\spam\eggs.png'
1.1 Importing os
import os
os.path.join('folder1','folder2','folder3','file.png')
'folder1\\folder2\\folder3\\file.png'
os.sep
'\\'
os.getcwd() # get current working directory
os.chdir('c:\\')
os.getcwd()
os.chdir('C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.5')
os.path.abspath('spam.png')
'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.5\\spam.png'
1.2 os.path.isabs() , os.path.relpath()
os.path.isbs('..\\..\\spam.png')
False
os.path.isabs('C:\\folder\\folder')
True
os.path.relpath('c:\\folder1\\folder2\\spam.png','c:\\folder1')
'folder2\\spam.png'
os.path.dirname('c:\\folder1\\folder2\\spam.png')
'c:\\folder1\\folder2'
os.path.basename('c:\\folder1\\folder2\\spam.png')
'spam.png'
os.path.basename('c:\\folder1\\folder2')
folder2
1.3 os.path.isfile() , os.path.isdir()
os.path.exists('c:\\folder1\\folder2')
False
os.path.exists('c:\\windows\\system32\\calc.exe')
True
os.path.isfile('c:\\windows\\system32\\calc.exe')
True
os.path.isfile('c:\\windows\\system32')
False
os.path.isdir('c:\\windows\\system32')
True
os.path.isdir('c:\\windows\\seenu')
False
1.4 os.path.getsize()
os.path.getsize('c:\\windows\\system32\\calc.exe')
918528
list the files inside a directory
os.listdir('c:\\srinivas')
total size of the files inside the folder
for filename in os.listdir('c:\\srinivas')
if not os.path.isfile(os.path.join('c:\\srinivas',filename)):
continue
totalsize = totalsize + os.path.getsize(os.path.join('c:\\srinivas',filename))
totalsize
1.5 os.makedirs()
os.makedirs('c:\\srinvas\\folder1\\folder2')
Recap :
- Files have a name and a path.
- The root folder is the lowest folder.
- In a file path, the folders and filename are separated by backslashes on Windows and forward slashes on Linux and Mac.
- Use the os.path.join() function to combine folders with the correct slash.
- os.getcwd() will return the current working directory.
- os.chdir() will change the current working directory.
- Absolute paths begin with the root folder, relative paths do not.
- The . folder represents "this folder", the .. folder represents "the parent folder".
- os.path.abspath() returns an absolute path form of the path passed to it.
- os.path.relpath() returns the relative path between two paths passed to it.
- os.makedirs() can make folders.
- os.path.getsize() returns a file's size.
- os.listdir() returns a list of strings of filenames.
- os.path.exists() returns True if the filename passed to it exists.
- os.path.isfile() and os.path.isdir() return True if they were passed a filename or file path.
2.Reading and Writing Plain Text Files
create a file hellworld.txt with content
#helloworld.txt
Hello World!
How are you?
helloFile = open('C:\srinivas\hellworld.txt') # it opens the files in readonly mode
helloFile.read()
'Hello World!\nHow are you?'
helloFile.close()
helloFile = open('C:\srinivas\hellworld.txt')
content=helloFile.read()
print(content)
Hello World!
How are you?'
helloFile.close()
2.1 readlines() Method - It returns the list of strings
helloFile = open('C:\srinivas\hellworld.txt')
helloFile.readlines()
['Hello world!\n','How are you?']
helloFile.close()
2.2 Write Mode - It overrides the existing with new values
pass the second parameter to the open as 'w'
helloFile = open('C:\srinivas\hello2.txt','w') # if the file does not exists it will create one
helloFile.write('Hello!!!!!')
12
###### writes the number of bytes it has written
helloFile.write('Hello!!!!!')
12
helloFile.write('Hello!!!!!')
12
helloFile.close()
helloFile.write('Hello!!!!!\n')
appleFile=open('apple.txt','w')
appleFile.write('Apple is not a vegetable.')
appleFile.close()
import os
os.getcwd()
appleFile = open('apple.txt','a')
appleFile.write('\n\nApple milkshake is declicious.')
appleFile.close()
2.3 shelve module can store Python values in a binary file
import shelve
shelfFile = shelve.open['mydata']
shelfFile['cats']=['zophie','Pooka','Simon','cleo']
shelfFile.close()
#check the current working directory, it will create 3 files
mydata.bak ,mydata.dat, mydata.dir
shelfFile = shelve.open('mydata')
shelfFile['cats']
shelfFile = shelve.open('mydata')
list(shelfFile.keys())
list(shelfFile.values())
mydata.bak
mydata.dat
mydata.dir
2.4 Append Mode: Appends the content to the txt file
helloFile = open('C:\srinivas\hellworld.txt','a')
Recap :
- The open() function will return a file object which has reading and writing โrelated methods.
- Pass โr' (or nothing) to open() to open the file in read mode. Pass โw' for write mode. Pass โa' for append mode.
- Opening a nonexistent filename in write or append mode will create that file.
- Call read() or write() to read the contents of a file or write a string to a file.
- Call readlines() to return a list of strings of the file's content.
- Call close() when you are done with the file.
- The shelve module can store Python values in a binary file.
- The shelve.open() function returns a dictionary-like shelf value.
3. Copying and Moving Files and Folders
- To work with copying and moving files and folders ,import shutil module
import shutil
shutil.copy('c:\\spam.txt','c:\srinivas')
#copy and rename the file
shutil.copy('c:\\spam.txt','c:\srinivas\spammodified.txt')
#copy entire folders and files
shutil.copytree('c:\delicious',c:\delicious_backup')
#output :'c:\delicious_backup'
#if wanted to move a file to a new location
shutil.move('c:\\spam.txt','c:\\delicious\\walnut')
#output : 'c:\delicious\walnut\spam.txt'
# there is nothing like shutil.rename, instead try the below one
shutil.move('c:\\delicious\\walnut\\spam.txt','c:\\delicious\\walnut\\eggs.txt'
4. Deleting the files
4.1 os.unlink() - to delete a file
import os
os.getcwd()
os.unlink('bacon.txt')
4.2 os.rmdir() -if any file exists in a folder and it will fail
os.rmdir('c:\\delicious')
it will fail if files existing in the folder
4.3 shutil.rmtree() => Deletes a folder and its entire contents.
import shutil
shutil.rmtree('c:\\delicious')
4.3.1 Dry Run
import os
os.chdir('C:\\Users\\Srini\\Desktop')
for filename in os.listdir() :
if filename.endswith('.txt'):
#os.unlink(filename)
print(filename)
4.4 sendtotrash module()
we need to install using pip
cd "c:\Program Files\Python 3.5\Scripts\
c:\Program Files\Python 3.5\Scripts> pip.exe install send2trash
import send2trash
send2trash.send2trash('c:\\users\srini\\desktop\\IMPORTANT_FILE!!!!.rxt'
it will delete the file and moves to trash
Recap:
- os.unlink() will delete a file.
- os.rmdir() will delete a folder (but the folder must be empty).
- shutil.rmtree() will delete a folder and all its contents.
- Deleting can be dangerous, so do a "dry run" first.
- send2trash.send2trash() will send a file or folder to the recycling bin.
Conclusion : Discussed about python - dictionaries used IDLE shell command for running the python code
๐ฌ If you enjoyed reading this blog post and found it informative, please take a moment to share your thoughts by leaving a review and liking it ๐ and share this blog with ur friends and follow me in linkedin
Top comments (0)