Google News
logo
Python File Input and File Output

Python provides numerous built-in functions that are readily available to us at the Python prompt.

Some of the functions like input() and print() are widely used for standard input and output operations respectively. Let us see the output section first.

Python Output Using print() function

We use the print() function to output data to the standard output device (screen).

We can also output data to a file, but this will be discussed later. An example use is given below.

>>> print('This sentence is output to the screen')
This sentence is output to the screen
>>> a = 9
>>> print('The value of a is : ', a)
The value of a is :  9
>>> 
The actual syntax of the print() function is
print (*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen). Here are an example to illustrate this.

>>> print (1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5, sep='*')
1*2*3*4*5
>>> print(1,2,3,4,5,sep='#',end='&')
1#2#3#4#5&
>>> 

Output formatting

The Output format can be done by using the str.format() method. This method is visible to any string object.

>>> x = 15
>>> y = 20
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 15 and y is 20
>>> 

Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).

>>> print('This is {0} and {1}'.format('Python Tutorial','Examples'))
This is Python Tutorial and Examples
>>> print('This is {1} and {0}'.format('Python Tutorial','Examples'))
This is Examples and Python Tutorial
>>> 

We can even use keyword arguments to format the string

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'FTL'))
Hello FTL, Goodmorning
>>> 

We can even format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.

>>> x = 15.4557756
>>> print ('The value of x is %3.2f' %x)
The value of x is 15.46
>>> print('The value of x is %3.4f' %x)
The value of x is 15.4558

Python Input

To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is

Syntax :
input([prompt])
where prompt is the string we wish to display on the screen. It is optional.
>>> number = input('Enter a number : ')
Enter a number : 27
>>> number
'27'
>>> 

Here, we can see that the entered value 27 is a string, not a number. To convert this into a number we can use int() or float() functions.

>>> int('27')
27
>>> float('27')
27.0
>>> 

This same operation can be performed using the eval() function. But it takes it further. It can evaluate even expressions, provided the input is a string.

>>> int('7+18')
Traceback (most recent call last):
  File "<pyshell#76>", line 1, in <module>
    int('7+18')
ValueError: invalid literal for int() with base 10: '7+18'
>>> eval ('7+18')
25
>>> 

Modes of File:

There are different modes of file in which it can be opened. They are mentioned in the following table :

ModeDescription
RIt opens in Reading mode. It is default mode of File. Pointer is at beginning of the file.
rbIt opens in Reading mode for binary format. It is the default mode. Pointer is at beginning of file.
r+Opens file for reading and writing. Pointer is at beginning of file.
rb+Opens file for reading and writing in binary format. Pointer is at beginning of file.
WOpens file in Writing mode. If file already exists, then overwrite the file else create a new file.
wbOpens file in Writing mode in binary format. If file already exists, then overwrite the file else create a new file.
w+Opens file for reading and writing. If file already exists, then overwrite the file else create a new file.
wb+Opens file for reading and writing in binary format. If file already exists, then overwrite the file else create a new file.
aOpens file in Appending mode. If file already exists, then append the data at the end of existing file, else create a new file.
abOpens file in Appending mode in binary format. If file already exists, then append the data at the end of existing file, else create a new file.
a+Opens file in reading and appending mode. If file already exists, then append the data at the end of existing file, else create a new file.
ab+Opens file in reading and appending mode in binary format. If file already exists, then append the data at the end of existing file, else create a new file.

Methods :

There are many methods related to File Handling. They are given in the following table :

MethodDescription
rename()It is used to rename a file. It takes two arguments, existing_file_name and new_file_name.
remove()It is used to delete a file. It takes one argument. Pass the name of the file which is to be deleted as the argument of method.
mkdir()It is used to create a directory. A directory contains the files. It takes one argument which is the name of the directory.
chdir()It is used to change the current working directory. It takes one argument which is the name of the directory.
getcwd()It gives the current working directory.
rmdir()It is used to delete a directory. It takes one argument which is the name of the directory.
tell()It is used to get the exact position in the file.