Files

File is a named location on disk to store related information. Python uses the file objects to interact with external files on the computer. These files could be of any format like text, binary, excel, audio, video files. Please note external libraries will be required to use some of the file formats.

Typically in python file operation takes place in the following order:

  1. Open a file
  2. Perform Read or Write operation
  3. Close the file

Creating a text file in Jupyter


In [1]:
%%writefile test.txt
This is a test file


Writing test.txt

Opening a file

Python has a built-in function called open() to open a file. This function returns a file handle that can be used to read or write the file accordingly.

Python allows a file to open in multiple modes. The following are some of the modes that can be used to open a file.

  • 'r' - open a file for reading
  • 'w' - open a file for writing, create the file if it does not exist
  • 'x' - open the file for exclusing creation
  • 'a' - open the file in append mode, contents will be appended to the end of the file, created if file does not exist
  • 't' - open a file in text format
  • 'b' - open a file in binary format
  • '+' - open a file for reading & writing (for updating)

In [11]:
# open the file in read mode
# f = open("C:/Python33/test.txt) # opens file in the specified full path
f = open('test.txt','r') # opens file in the current directory in read mode
print(f.writable()) # Is the file writable - False
print(f.readable()) # Is the file readable - True
print(f.seekable()) # Is random access allowed - Must be True
print(f.fileno())


False
True
True
57

In [ ]:
# Different ways of opening the files

# f = open('test.txt') # equal to 'r' or 'rt' (read text)
# f = open('test.txt','w') # write in text mode
# f = open('image.bmp','r+b') # read and write in binary mode

# using encoding type
# f = open("test.txt", mode="r", encoding="utf-8")

Closing File

Files need to be properly closed so that the resources can be released othewise they will be tied up unnecessarily.


In [17]:
# close the file using close function
f.close()


False

Opening & Closing Files in Safe Way


In [23]:
# Using Exception Method
try:
    f = open("test.txt",mode="r",encoding="utf-8")
    # perform file operations
    f.seek(0)
    print(f.read(4))
finally:
    f.close()


This

In [24]:
# Using 'with' Method
# Explicit close is not required. File is closed implicitly when the block inside 'with' is exited.
with open('test.txt',encoding='utf-8') as f:
    # perform file operations
    print(f.read())


This is a test file

Reading a file


In [34]:
with open('test.txt') as f:
    f.seek(0) # move the file pointer to start of the file
    print(f.tell())
    print(f.read(4)) # read the first 4 words
    print(f.tell())  # print the current file handler position
    print(f.read())  # read till end of file
    print(f.tell())
    print(f.read())  # this will print nothing as it reached end of file
    print(f.tell())


0
This
4
 is a test file
19

19

Reading File Line by Line

Lets create a simple file using Jupyter macro %%writefile


In [36]:
%%writefile test1.txt
Line 1
Line 2
Line 3


Writing test1.txt

In [45]:
with open('test1.txt') as f:
    print(f.readline(), end = '')  # Prints the 1st Line
    print(f.readline())  # Prints the 2nd Line
    print(f.readline())  # Prints the 3rd Line
    print(f.readline())  # prints blank lines
    print(f.readline())


Line 1
Line 2

Line 3



In [39]:
with open('test1.txt') as f:
    print(f.readlines())


['Line 1\n', 'Line 2\n', 'Line 3']

In [40]:
# using for loop
for line in open('test1.txt'):
    print(line, end='') # end parameter to avoid printing blank lines


Line 1
Line 2
Line 3

In [51]:
with open('newfile.txt','w+') as f:
    f.writelines('New File - Line 1')
    f.writelines('New File - Line 2')
    f.seek(0)
    print(f.readlines())


['New File - Line 1New File - Line 2']

In [56]:
try:
    f = open('newfile.txt','a')
    f.write('this is appended line')
    f.close()
    f = open('newfile.txt','r')
    print(f.read())
finally:
    f.close()


New File - Line 1New File - Line 2this is appended linethis is appended linethis is appended linethis is appended linethis is appended line