DEV Community

Srinivasulu Paranduru
Srinivasulu Paranduru

Posted on

Python: Part3 - Files

1.Filenames and Absolute/Relative paths:

'c:\\spam\\eggs.png'

Enter fullscreen mode Exit fullscreen mode

'c:\\spam\\eggs.png'

print('\\')

Enter fullscreen mode Exit fullscreen mode

\

r'c:\spam\eggs.png'

Enter fullscreen mode Exit fullscreen mode

'c:\spam\eggs.png'

1.1 Importing os

import os
os.path.join('folder1','folder2','folder3','file.png')

Enter fullscreen mode Exit fullscreen mode

'folder1\\folder2\\folder3\\file.png'

os.sep
Enter fullscreen mode Exit fullscreen mode

'\\'

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'

Enter fullscreen mode Exit fullscreen mode

1.2 os.path.isabs() , os.path.relpath()

os.path.isbs('..\\..\\spam.png') 
Enter fullscreen mode Exit fullscreen mode

False

os.path.isabs('C:\\folder\\folder')
Enter fullscreen mode Exit fullscreen mode

True

os.path.relpath('c:\\folder1\\folder2\\spam.png','c:\\folder1')
Enter fullscreen mode Exit fullscreen mode

'folder2\\spam.png'

os.path.dirname('c:\\folder1\\folder2\\spam.png')
Enter fullscreen mode Exit fullscreen mode

'c:\\folder1\\folder2'

os.path.basename('c:\\folder1\\folder2\\spam.png')
Enter fullscreen mode Exit fullscreen mode

'spam.png'

os.path.basename('c:\\folder1\\folder2')
Enter fullscreen mode Exit fullscreen mode

folder2

1.3 os.path.isfile() , os.path.isdir()

os.path.exists('c:\\folder1\\folder2')
Enter fullscreen mode Exit fullscreen mode

False

os.path.exists('c:\\windows\\system32\\calc.exe')
Enter fullscreen mode Exit fullscreen mode

True

os.path.isfile('c:\\windows\\system32\\calc.exe')
Enter fullscreen mode Exit fullscreen mode

True

os.path.isfile('c:\\windows\\system32')
Enter fullscreen mode Exit fullscreen mode

False

os.path.isdir('c:\\windows\\system32')
Enter fullscreen mode Exit fullscreen mode

True

os.path.isdir('c:\\windows\\seenu')
Enter fullscreen mode Exit fullscreen mode

False

1.4 os.path.getsize()

os.path.getsize('c:\\windows\\system32\\calc.exe')
Enter fullscreen mode Exit fullscreen mode

918528

list the files inside a directory

os.listdir('c:\\srinivas')
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

1.5 os.makedirs()

os.makedirs('c:\\srinvas\\folder1\\folder2')

Enter fullscreen mode Exit fullscreen mode

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?
Enter fullscreen mode Exit fullscreen mode
helloFile = open('C:\srinivas\hellworld.txt') # it opens the files in readonly mode
helloFile.read()

Enter fullscreen mode Exit fullscreen mode

'Hello World!\nHow are you?'

helloFile.close()

Enter fullscreen mode Exit fullscreen mode

helloFile = open('C:\srinivas\hellworld.txt')
content=helloFile.read()
print(content)

Enter fullscreen mode Exit fullscreen mode

Hello World!
How are you?'

helloFile.close()

Enter fullscreen mode Exit fullscreen mode

2.1 readlines() Method - It returns the list of strings

helloFile = open('C:\srinivas\hellworld.txt')
helloFile.readlines()

Enter fullscreen mode Exit fullscreen mode

['Hello world!\n','How are you?']

helloFile.close()

Enter fullscreen mode Exit fullscreen mode

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!!!!!')

Enter fullscreen mode Exit fullscreen mode

12 ###### writes the number of bytes it has written

helloFile.write('Hello!!!!!')

Enter fullscreen mode Exit fullscreen mode

12

helloFile.write('Hello!!!!!')

Enter fullscreen mode Exit fullscreen mode

12

helloFile.close()

Enter fullscreen mode Exit fullscreen mode

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()

Enter fullscreen mode Exit fullscreen mode

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())


Enter fullscreen mode Exit fullscreen mode

mydata.bak
mydata.dat
mydata.dir

2.4 Append Mode: Appends the content to the txt file

helloFile = open('C:\srinivas\hellworld.txt','a')

Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

4. Deleting the files

4.1 os.unlink() - to delete a file

import os
os.getcwd()
os.unlink('bacon.txt') 

Enter fullscreen mode Exit fullscreen mode

4.2 os.rmdir() -if any file exists in a folder and it will fail

os.rmdir('c:\\delicious')

Enter fullscreen mode Exit fullscreen mode

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')

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode
import send2trash
send2trash.send2trash('c:\\users\srini\\desktop\\IMPORTANT_FILE!!!!.rxt'

Enter fullscreen mode Exit fullscreen mode

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)