1 of 27

File Input Output�Python

Satishkumar L. Varma

Professor, Department of Computer Engineering

PCE, New Panvel

www.sites.google.com/site/vsat2k

2 of 27

Outline

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Printing to the Screen
  • Reading Keyboard Input
  • Opening and Closing Files
  • Reading and Writing Files
  • File Positions
  • Renaming and Deleting Files
  • Directories in Python

2

3 of 27

Function – Print: Print to the Screen

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

3

  • print
    • function converts the expression passed to a string and
    • writes the result to standard output as
  • Example
    • Code: print(“This is my first program,", “isn't it?“)
    • Output: This is my first program, isn't it?

4 of 27

Reading Keyboard Input

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Provides 2 built-in functions to read a line of text from standard i/p
  • Input by default comes from the keyboard
  • raw_input() Function:
    • str = raw_input("Enter your input: ");
    • print("Received input is : ", str)
  • input() function:
    • Assumes the input is a valid Python expression and returns evaluated result:
      • str = input("Enter your input: ");
      • print("Received input is : ", str)
    • Produce following result against the entered input:
      • Enter your input: [x*5 for x in range(2,10,2)]
      • Recieved input is : [10, 20, 30, 40]

4

5 of 27

Opening and Closing Files

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Reading and writing to/from actual data files
  • Python provides built-in open() function to open file
  • Function creates a file object to call other supported methods
  • Syntax:

file object = open(file_name [, access_mode][, buffering])

5

6 of 27

open() function Paramters

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • file object = open(file_name [, access_mode][, buffering])
  • file_name
    • It is a string value
    • It contains the name of the file that you want to access
  • access_mode
    • It determines the mode in which the file has to be opened
    • Modes are read, write append etc (see list in the next slide)
    • It is optional parameter and the default file access mode is read (r)
  • buffering
    • If value = 0, no buffering
    • If value = 1, line buffering will be performed while accessing a file
    • If value > 1, then buffering is performed with indicated buffer size
    • If value = -ve , default behaviour of the system (default behaviour)

6

7 of 27

Modes of Opening a File

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

7

Modes

Description

r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

rb

Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

r+

Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

rb+

Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

w

Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

wb

Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

w+

Opens a file for both writing and reading. Overwrites the existing file if file exists. If the file does not exist, creates a new file for reading and writing.

8 of 27

Modes of Opening a File

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

8

Modes

Description

wb+

Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

a

Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

9 of 27

open() and close() File Object Attributes

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • One file object is created if a file is successfully opened
  • Object is used to get various information related to that file
  • File object has following list of all attributes related to file

  • Close the file

fileObject.close()

9

Attribute

Description

file.closed

Returns true if file is closed, false otherwise.

file.mode

Returns access mode with which file was opened.

file.name

Returns name of the file.

10 of 27

Example: openCloseFile.py

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

# Code:

f = open("testFile.txt", "wb")

print("Name of the file : ", f.name)

print("Closed or not : ", f.closed)

print("Opening mode : ", f.mode)

f.close()

print("Closed or not : ", f.closed)

# Output:

Name of the file : testFile.txt

Closed or not : False

Opening mode : wb

Closed or not : True

10

11 of 27

Reading From File

  • read()
    • reads in the whole text – only advisable if the text is small!
  • readline()
    • reads one line at a time; the ‘\n’ is kept
  • readlines()
    • reads in the whole text using readline()
    • returns a list of strings
  • Code:

f = open("myDocument.txt", "r")

str1 = f.read()

#str2 = f.readline()

#str3 = f.readlines()

print(str1)

f.close()

11

12 of 27

Writing into File

  • write("string")
    • It writes any string to an open file
    • It is important to note that Python strings can have binary data and not just text
    • It does not add a newline character ('\n') to the end of string
  • writelines(<list>)
    • writes a list or any other sequence to a file
    • it does not add newlines
  • Syntax:

myList = ['abc', 'xyz', 'lmn', ' ok.' ]

f = open("myDocument1.txt", "w")

#str1 = f.read()

for i in myList:

f.write(i)

f.close()

12

13 of 27

For Loop and File Input

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

# For Loop and File Input

import fileinput

for line in fileinput.input('myDocument.txt'):

print(line)

13

14 of 27

Piping with Files

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • It allows to pipe input from terminal through our python program

# Code:

import fileinput

for i in fileinput.input():

print(i)

14

15 of 27

Iterating over File Contents

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Python handles the closing & there’s no explicit file variable
  • A very simple way to iterate is to use the following convention:

# Code

for i in open('myDocument.txt'):

print(i)

15

16 of 27

File Positions

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • tell() method
    • tells you the current position within the file in other words, the next read or write will occur at that many bytes from the beginning of the file:
  • seek(offset[, from]) method
    • changes the current file position
    • offset argument indicates the number of bytes to be moved
    • from argument specifies the reference position from where the bytes are to be moved.
  • If from = 0, it means use the beginning of the file as the reference position
  • If from = 1, it uses the current position as the reference position
  • If from = 2, the end of the file would be taken as the reference position

16

17 of 27

File Positions

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

# Example of seek()

f = open("myDocument.txt", "r+")

str = f.read(15);

print("Read String is : ", str)

position = f.tell();

print("Current file position : ", position)

position = f.seek(0, 0);

str = f.read(15);

print("Again read String is : ", str)

f.close()

17

18 of 27

Renaming Files

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Python os module provides method
  • It helps to perform file-processing operations, such as renaming and deleting files.
  • Import it to use any related functions
  • rename()
    • Takes 2 arguments, current filename and new filename
    • Syntax: os.rename(current_file_name, new_file_name)
    • Code:

import os

os.rename( "test1.txt", "test2.txt" )

18

19 of 27

Deleting Files

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • delete()
    • To delete files by supplying the name of the file to be deleted as the argument
  • Syntax:

os.remove(file_name)

  • Example:

import os

os.remove("test2.txt")

19

20 of 27

Directories in Python

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • All files are contained within various directories, and Python has no problem handling these too.
  • The os module has several methods that help you create, remove, and change directories.
  • mkdir()
    • Used to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.
  • Syntax:

os.mkdir("newdir")

  • Example:

import os # Create a directory "test"

os.mkdir("test")

20

21 of 27

Directories in Python

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • chdir()
    • Used to change the current directory
    • It takes an argument - name of the directory to make the current directory
  • Syntax:

os.chdir("newdir")

  • Example:

import os

os.chdir("/home/newdir")

21

22 of 27

Directories in Python

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • getcwd()
    • It displays the current working directory
  • Syntax:

os.getcwd()

  • Example:

import os

os.getcwd()

22

23 of 27

Directories in Python

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • rmdir()
    • It deletes the directory passed as an argument in the method
    • All contents should be removed before removing a directory
  • Syntax:

os.rmdir('dirname')

  • Example:

import os

os.rmdir( "/tmp/test" )

23

24 of 27

File & Directory Related Methods

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

  • Important sources to handle and manipulate files & directories on Windows and Unix OS
    • File Object Methods
      • It provides functions to manipulate files
    • OS Object Methods
      • It provides methods to process files as well as directories

24

25 of 27

Outline

Satishkumar L. Varma, PCE New Panvel www.sites.google.com/site/vsat2k

25

26 of 27

References

26

Satishkumar Varma, PCE www.sites.google.com/site/vsat2k

  • Zed A. Shaw, “Learn Python the Hard Way”, Third Edition, Addison-Wesley, 2014.
  • Bruno Dufour, “A Comprehensive Introduction to Python Programming and GUI Design Using Tkinter”, McGill Univeristy SOCS.
  • JOHN E. GRAYSON, “Python and Tkinter Programming”, Manning Publications, 2000.
  • Burkhard A. Meier, “Python GUI Programming Cookbook”, Packt Publishing, 2015.

27 of 27

Thank You.

Satishkumar Varma, PCE www.sites.google.com/site/vsat2k

27