Python File Handling

The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non-volatile) after the program termination.

The open() Function

This function creates a file object, which would be utilized to call other support methods associated with it.

Syntax:-

file object = open(file_name ,access_mode)

Here are the parameter details:-

  • file_name:-The file_name argument is a string value that contains the name of the file that you want to access.
  • access_mode:-The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. A complete list of possible values is given below in the table. This is an optional parameter and the default file access mode is read (r).

File Opening Modes

Sr.No. Modes & Description
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2 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.
3 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.

Example:-

# Open a file
fo = open("foo.txt", "w")
print ("Name of the file: ", fo.name)
print ("Closed or not: ", fo.closed)
print ("Opening mode: ", fo.mode)
fo.close()

The write() Function

After you obtain the file object with the open() function, you can use the write() method to write any string to the file represented by the file object.
The write() method does not add a newline character ('\n') to the end of the string.

Syntax:-

fileObject.write(string)

Example:-

# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opened file
fo.close()

Appending to a File

When any existing file is opened in 'w' mode to store additional text, its earlier contents are erased. Whenever a file is opened with write permission, it is treated as if it is a new file. To add data to an existing file, use 'a' for append mode.

Syntax:-

fileobject = open(file_name,"a")

Example:-

# Open a file in append mode
fo = open("foo.txt", "a")
text = "TutorialsPoint has a fabulous Python tutorial"
fo.write(text)
# Close opened file
fo.close()

Python - Read Files

To programmatically read data from a file using Python, it must be opened first.To read data from the opened file, use read() method of the File object. It is important to note that Python strings can have binary data apart from the text data.

Syntax:-

fileObject.read()

Example:-

# Open a file
fo = open("foo.txt", "r")
text = fo.read()
print (text)
# Close the opened file
fo.close()

File Functions


The seek() Method

The method seek() sets the file's current position at the offset.

Syntax:-

fileObject.seek(offset)

Example:-

# Open a file in read-write mode
fo=open("foo.txt","w")
fo.write("This is a rat race")
fo.seek(10)
data=fo.read(3)
fo.seek(10)
fo.write('cat')
fo.seek(0)
data=fo.read()
print (data)
fo.close()

rename() Method

The rename() method takes two arguments, the current filename and the new filename.

Syntax:-

os.rename(current_file_name, new_file_name)

Example:-

import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )

remove() Method

You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.

Syntax:-

os.remove(file_name)

Example:-

import os
# Delete file test2.txt
os.remove("text2.txt")

mkdir() Method

You can use the mkdir() method of the os module 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")

chdir() Method

You can use the chdir() method to change the current directory. The chdir() method takes an argument, which is the name of the directory that you want to make the current directory.

Syntax:-

os.chdir("newdir")

Example:-

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

getcwd() Method

The getcwd() method displays the current working directory.

Syntax:-

os.getcwd()

Example:-

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

rmdir() Method

The rmdir() method deletes the directory, which is passed as an argument in the method.Before removing a directory, all the contents in it should be removed.

Syntax:-

os.rmdir('dirname')

Example:-

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

flush() Method

The method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.

Syntax:-

fileObject.flush()

Example:-

# Open a file
fo = open("foo.txt", "w")
print ("Name of the file: ", fo.name)
# Here it does nothing, but you can call it with read operation.
fo.flush()
# Close the opened file
fo.close()

fileno() Method

The method fileno() returns the integer file descriptor that is used by the underlying implementation to request I/O operations from the operating system.

Syntax:-

fileObject.fileno()

Example:-

# Open a file
fo = open("foo.txt", "w")
print ("Name of the file: ", fo.name)
fid = fo.fileno()
print ("File Descriptor: ", fid)
# Close the opened file
fo.close()

isatty() Method

The method isatty() returns True if the file is connected (is associated with a terminal device) to a tty(-like) device, else False.

Syntax:-

fileObject.isatty()

Example:-

# Open a file
fo = open("foo.txt", "w")
print ("Name of the file: ", fo.name)
ret = fo.isatty()
print ("Return value : ", ret)
# Close the opened file
fo.close()

next() function

File object in Python 3 does not support next() method. Python 3 has a built-in function next() which retrieves the next item from the iterator by calling its __next__() method.

Syntax:-

next(iterator)

Example:-

f=open("foo.txt","r")
while True:
try:
line=next(f)
print (line)
except:
StopIteration
break
f.close()

readline() Method

The method readline()reads one entire line from the file.

Syntax:-

fileObject.readline( size )

Example:-

# Open a file
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
line = fo.readline(5)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()

readlines() Method

The method readlines() reads until EOF using readline() and returns a list containing the lines.

Syntax:-

fileObject.readlines( sizehint )

Example:-

# Open a file
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
line = fo.readlines(2)
print ("Read Line: %s" % (line))
# Close the opened file
fo.close()

tell() Method

The method tell() returns the current position of the file read/write pointer within the file.

Syntax:-

fileObject.tell()

Example:-

fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
pos=fo.tell()
print ("current position : ",pos)
# Close the opened file
fo.close()

truncate() Method

The method truncate() truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.

Syntax:-

fileObject.truncate( [ size ])

Example:-

fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))
# Close opened file
fo.close()

writelines() Method

The method writelines() writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value.

Syntax:-

fileObject.writelines( sequence )

Example:-

# Open a file in read/write mode
fo=open("foo.txt","r")
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
fo.seek(0,0)
while True:
try:
line=next(fo)
print (line)
except:
StopIteration
break
fo.close()