Handling Files in Python

In Python, files are accessed using the file objects. The file needs to be opened first.

This is done with the help of the open() function. The function takes the name of the file and the mode as its arguments. The open function returns an object of the file. The object then uses the library functions to read the file, write into it or append it. Finally, the memory space occupied by the object is freed using the close() function.

open()

The first argument is the name of the file, the second the mode in which the file is opened. The path can be relative or absolute. The access mode is the mode in which the file will be opened.

In the read mode (“r”) the file is opened, if it exists. The write mode (“w”) opens the file for writing. If the file already exists, the existing contents of the file are truncated. The append mode (“a”) opens the file for writing but does not truncate the existing contents. In this mode if the file does not exist, it will be created.

read()

The function reads bytes in a string. It may take an integer argument indicating the number of bytes to read. If the argument is -1, the files must be read to the end. Also if no argument is given, the default is taken as -1.

readline() and readlines()

The readline() method is used to read a line until the newline character is read. The newline character is retained in the string that is returned.

The readlines() method reads all the lines from a given file and returns a list of strings.

write() and writelines()

The write() method writes the string in a given file.

The writelines() method writes a list of strings to the file.

seek()

The seek() method takes the cursor to the starting position in the given file. The position is decided with respect to the offset given. The offset can be 0, 1, or 2. “0” indicates the beginning of the file. The value “1” indicates the current position and the value “2” indicates the end of the file.

tell()

The tell() is complementary to the seek() function. The function returns the position of the cursor.

close()

The close() function closes the file. The object should be assigned to another file after it is closed. Though Python closes a file after a program finishes, it is advisable to close the file when the required task is accomplished.