Python Files and Directories

Files – basically a sequence of binary in computer language. Files can be a text format (.txt), CSV, Excel and many more.

Directories – The place where you keep all your files are called directories. It is a method of arranging a files. In Windows it can be a folder.

Set of operation on files

  1. Read a file.
  2. Write on a file – if file is empty, if not, it can be Overwritten.
  3. Overwrite a file.
  4. append on a file. – after the end of the file, if it is not empty.

open() Method in Python
You have to open a file before performing above operations.

Syntax

fileobject = open(filename, mode)

filename – represents the name of the file

mode has two letters, first it can be:
1) r for read.
2) w for write – if file is empty, if not, it will create the new one, if exist it is overwritten.
3) a for append. – if file exist write after the end.
4) x – write only – if file does not already exist.

Second letter represents:
1) t for nothing.
2) b means binary.

close() method:

Once you open the file, it is your duty to close the file to freed all the memory occupied, isn’t it.

Syntax

filename.close()

Examples

#open file and create it, if it dosen't exist.
fileobject=open('Test.txt', 'wt')

#to close the file
fileobject.close()

write() function to write on a file after it opens

fileobject=open('Test.txt', 'wt')
fileobject.write("Python is the best")

Output # returns number of byte returns

18

Write using print Statement, but preferable method is write()

fileobject=open('prints.txt', 'wt')
print("Examine the print statement", file = fileobject)

fileobject.close()

Write MyStory on a file using write() method

It has following components

  1. Assign a story with a lines of sentences below, ”’ ”’ represents opening and closing of multiple line statement.
  2. Create an Empty text file with a name MyStory – ‘wt’ in open() method do that, if file already is not present.
  3. Finally use write() method to write story on MyStory file.
  4. The write() method returns number of bytes written and it also does not add any spaces or newlines, the way print statement does.

>>> Story = ''' My name is Ankit,...
And i am the master of python, ...
And i love this language '''

>>> print(Story)

#Output
 My name is Ankit,...
And i am the master of python, ...
And i love this language 


>>> fileobject = open('MyStory','wt')

>>> fileobject.write(Story)

#Output
82

>>> fileobject.close()

Remember – if we try to open MyStory again with ‘xt’, it will not overwrite the file with write().
It will display the following error.

fileobject = open('MyStory','xt')

Output

Traceback (most recent call last):
File “”, line 1, in
fileobject = open(‘MyStory’,’xt’)
FileExistsError: [Errno 17] File exists: ‘MyStory’

Read MyStory from a file using read() method

Read() method – reads all the lines at once, So we should be careful, it may be gb’s of data.
Good way is to read line by line using readline() method.

Story = ''' My name is Ankit,...
And i am the master of python, 
...And i love this language '''


Reads = open('MyStory','rt')

Reads.read()

Output

' My name is Ankit,...\nAnd i am the master of python, \n...And i love this language '

readline() method to read line by line text

Story = ''' My name is Ankit,...
And i am the master of python, 
...And i love this language '''


Reads = open('MyStory','rt')

Reads.readline()


#Output 

' My name is Ankit,...\n'

readlines() methodApply for statement above to read all the data line by line using readlines()

Reads = open('MyStory','rt')   
All_Lines = Reads.readlines()   # readlines() read all lines

Reads.close()               

for line in All_Lines:        # Read lines one by one from all Lines and print.
    print(line, end='')       # end= '' in print to supress the automatic new line.

Output

My name is Ankit,...
And i am the master of python, 
...And i love this language 

Read and Write binary file
Create a binary file for 128 bytes and write it on a file and then read from the file.

bindata = bytes(range(0,128) )
       #Create a binary data using range()

BinaryFile = open('BinaryFile','wb')
BinaryFile.write(bindata)            #Write Binary Data on a file

BinaryFile.close()

#Output
128      

For range() method visit the link below:
https://effortlesspython.com/python-range-function/

Read a Binary file
You can read the binary file represented below.

BinaryFile = open('BinaryFile','rb')
BinaryFile.read()

BinaryFile.close()

Output

b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'

seek( ) and tell( ) method

tell() method tells you where are you while reading a file.

bindata = bytes(range(0,128) )
       #Create a binary data using range()

BinaryFile = open('BinaryFile','wb')
BinaryFile.write(bindata)            #Write Binary Data on a file

BinaryFile.tell()  # Don't use it after the close() method

seek() method helps you to move another byte offset in the file.

BinaryFile.seek(127)   # add it to the very last in the code above.

# Output

127

Automatically closing a file using with

It will block the code under the context manager, below the first line of code and then close.

with open('BinaryFile','rb')
BinaryFile.read()

Python File Operations :
Python file operation is similar to unix file operations. python uses os.path module functions and also uses functions from newer pathlib module.

Please visit the link below to understand the file operations.

https://effortlesspython.com/python-file-operations/

1 thought on “Python Files and Directories”

Leave a Comment