Python file i/o With Detailed Explanation

This article entitled Python file i/o is a continuation of the previous article entitled Python Modules.

These articles cover all the essential Python file i/o functions available in Python and some of the operations with the help of an advanced example.

What is a Python file i/o?

In Python, file i/o is an in-built function that stands for input and output that can be used for writing and reading a file.

A file i/o operations are listed below, and it happens in the sequence stated.

  • Used to open the file
  • Used to read and write file operation
  • Used to close a file

Python open function

Python provides an in-built function named open() that can be used to open a file before you can write and read the file.

Function, this built-in function created an object file that can be utilized to call the other support method that can be associated with it.

Syntax

file object = open(file_name [, access_mode][, buffering])
ParameterDescription
file_nameA file_name is a parameter string value argument that contains the file name that you want to access.
access_modeAn access mode will determine in which mode the file has need to be opened for example write, read and append.
bufferingOnce the buffering value will set to 0, there will be no buffering will takes place. But once the buffering value is 1, The line buffering will be performed while the file is accessing. If the buffering value you specify is an integer and greater than 1, then the action buffering will be performed with an indicated buffer size. If the value is negative it means that the buffer size is the default system.

The following is a list of types of modes for opening a file.

ModesDescription
rThese modes are used to open a file for reading only, the pointer file was placed at the beginning of the file and this mode is the default.
rbThese modes are used for reading a binary format, the pointer file was placed at the beginning of the file and this mode is the default.
r+These modes are used to open for both writing and reading and the pointer file was placed at the beginning of a file.
rb+These modes are used to open a file from both writing and reading a binary format, the pointer files were placed at the beginning of the file.
wThese modes are used to open a file for writing only it will overwrite a file once the file already exists. But once a file doesn’t exist it will create a new file for writing.
wbThese modes are used to open a file for only writing in a binary format it will overwrite a file once the file already exists. But once a file doesn’t exist it will create a new file for writing.
w+These modes are used to open a file for both reading and writing it will overwrite a file once the file already exists. But once a file doesn’t exist it will create a new file for writing and reading.
wb+These modes are used to open a file for both readings and write a binary format it will overwrite a file once the file already exists. But once a file doesn’t exist it will create a new file for writing and reading.
aThese modes are used to open a file for appending a file pointer, a file pointer will be at the end of the file if exists and the file is in the append mode. ut once a file doesn’t exist it will create a new file for writing.
abThese modes are used to open a file for appending a binary format and the pointer file will be at the end once the file already exists meaning the file is in the append mode. But once a file doesn’t exist it will create a new file for writing.
a+These modes are used to open a file for both readings and appending. The file pointer will be at the end if the file exists. But once a file doesn’t exist it will create a new file for writing.
ab+These modes are used to open a file for both readings and appending a binary format The file pointer will be at the end if the file exists. But once a file doesn’t exist it will create a new file for writing and reading.

Python file object attributes

For instance, if the file is opened and you have a one-object file, you can easily get the various information that is related to that file.

The following are the lists of all the attributes that are related to the file object.

AttributeDescription
file.closedThese attributes will return true once the file is close, otherwise false.
file.modeThese attributes will return an access mode to the file that is opened.
file.nameThese attributes will return the file name
file.softspaceThese attributes will return false once the space is required explicitly with a print, otherwise true.

Example

# Open a file
imp = open("important.txt", "wb")
print ("Name of the file: ", imp.name)
print ("Closed or not : ", imp.closed)
print ("Opening mode : ", imp.mode)
print ("Softspace flag : ", imp.softspace)

Output

Name of the file:  important.txt
Closed or not :  False
Opening mode :  wb
Softspace flag :  0

Python close() method

Python close() method is a file object that is used to flush any unwritten information and exit the object file after there is no more writing will be done.

Further, Python will automatically close the file once the reference object of the file will be reassigned to another file. It was good practice if you use the close() method for closing the file.

Syntax

fileObject.close()

Example

# Open a file
imp = open("important.txt", "wb")
print "Name of the file: ", imp.name

# Close open file
imp.close()

Output

Name of the file:  important.txt

Python write() method

The Python write() method is used to write any string to open the file. Just always put in mind that Python strings can have a data binary and not just a text.

Further, the write() method doesn’t add a new line of character backslash n (‘\n’) at the end of the string.

Syntax

fileObject.write(string)

Example

# Open a file
imp = open("important.txt", "wb")
fo.write( "True heroes use sourcecodehero.\nYeah its great!!\n")

# Close opend file
imp.close()

Output

True heroes use sourcecodehero
Yeah its great!!

Python read() method

Python read() method is used to read a string from the open file. Just always remember that Python strings can have (binary data) apart from (text data).

Syntax

fileObject.read([count])

Example

# Open a file
imp = open("important.txt", "r+")
str = imp.read(10);
print ("Read String is : ", str)
# Close opend file
imp.close()

Output

Read String is :  True heroes use sourcecodehero

File positions in Python

The tell() method in Python is used to tell the current position of the within. In simple words, the next write and read will occur in bytes from the start of the file.

A seek(offset[, from]) is a method that can be used to change the position of the current file. An offset argument will indicate the number of bytes that will be moved. The (from) argument will specify the position reference from the bytes to be moved.

Once the (from) was set to 0, It simply means that the beginning of the file was a position reference and 1 meant to use the current position as the position reference, and once it was set to 2 it means the end of the file will be taken as the position reference.

Example

# Open a file
imp = open("important.txt", "r+")
str = imp.read(10)
print ("Read String is : ", str)

# Check current position
position = imp.tell()
print ("Current file position : ", position)

# Reposition pointer at the beginning once again
position = imp.seek(0, 0);
str = imp.read(10)
print ("Again read String is : ", str)
# Close opend file
imp.close()

Output

Read String is :  True heroes use sourcecodehero
Current file position :  10
Again read String is :  True heroes use sourcecodehero 

Output to a screen in Python

The simplest way for producing an output in Python is with the use of the statement named (print) that can allow you to pass zero or multiple expressions that were separated by a commas

Further, the function can convert expressions that pass on the string and then write the result into the standard output.

Example

print ("Python complete tutorial for true heroes by sourcecodehero")

Output

Python complete tutorial for true heroes by sourcecodehero

Read keyboard input in Python

To read keyboard input in Python can be simply done by the two in-built functions that will be used for reading a line f text from the input standard.

  • input
  • raw_input

Python input function

The Python input is a function that is equivalent to the raw_input, But it was assumed that the input should be valid in the expression in Python and will return the result that was evaluated.

Example

input = input("Enter your fullname: ")
print ("Your fullname is : ", input)

Output

Enter your fullname: Glenn Magada Azuelo
Your fullname is :  Glenn Magada Azuelo

Python raw_input function

A raw_input is a function in Python that reads a single line from the input standard and will return as a string and then remove all the newline that is trailing.

Example

input = raw_input("Enter your fullname: ")
print ("Your fullname is : ", input)

Output

Enter your fullname: Glenn Magada Azuelo
Your fullname is :  Glenn Magada Azuelo

Renaming and Deleting files in Python

In Python, the os module is a method that provides a method that will help you from performing operations in file processing.

Further, in order to use this module you will need to import it first, then call the functions that are related to your needs.

Python rename() method

A method named rename() will takes two arguments, the new filename and the filename that is current.

Syntax

os.rename(current_file_name, new_file_name)

Example

import os

# Rename a file from sampleOne.txt to sampleTwo.txt
os.rename( "sampleOne.txt", "sampleTwo.txt" )

Python remove() method

The remove() method can be used to delete or remove files simply by supplying the name of the (file) that will be deleted as an argument.

Syntax

os.remove(file_name)

Example

import os

# Delete file sample.txt
os.remove("sample.txt")

Python Directories

All the Python files are contained various directories and handling these directories is not a problem. The several methods of the os module can be helpful for creating, removing, and changing directories.

Python mkdir() method

The mkdir() method of the os module is used to create a directory in the present directory. You just need to fill in an argument on this method that contains the name of the created directory.

Syntax

os.mkdir("newdir")

Example

import os

# Create a directory "sample"
os.mkdir("sample")

Python chdir() method

The chdir() method is used to change the present directory and this method takes an (arguments) the name of the directory which you want to create the present directory.

Syntax

os.chdir("newdir")

Example

import os

# Changing a directory to "index/newdir"
os.chdir("/index/newdir")

Python getcwd() method

A getcwd() is a method that displays the present directory that is working.

Syntax

os.getcwd()

Example

import os

# This would give the location of the present directory
os.getcwd()

Python rmdir() method

The Python rmdir() method is used to delete a directory that is passed as a method in the arguments. Keep in mind that before removing a directory, all the contents or files within should be removed.

Syntax

os.rmdir('dirname')

Example

import os

# This would  remove "/tmp/sample"  directory.
os.rmdir( "/tmp/sample"  )

Summary

In summary, you have read about Python file i/o. We also discussed in this article what is a Python file i/o, open function, file object attributes, close() method, read() method, write() method, file positions, two keyboard functions, and different Python directories.

I hope this article could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment