File objects in Python can be used to access not only normal disk files, but also any other type of “file” that uses that abstraction. The open() built-in function returns a file object that is then used for all succeeding operations on the file in question. There are a large number of other functions that return a file or file-like object. One primary reason for this abstraction is that many input/output data structures prefer to adhere to a common interface in order to maintain consistency. In this article, we will learn about working with files in python.

open() and file()

  • As the key to opening file doors, the open() [and file()] built-in function provides a general interface to initiate the file input/output (I/O) process.
  • Syntax for the open() built-in function :
Copy to Clipboard
  • The fileName is a string which contains the name of the file to open. It can be a relative or absolute/full pathname. The access_mode is an optional variable, which is also a string, that consist of a set of flags indicating in which mode file will open. The default access_mode is ‘r’.
  • The other optional argument, buffering, is used to indicate the type of buffering that should be performed when accessing the file.
  • A value of 0 means no buffering should occur, a value of 1 signals line buffering, and any value greater than 1 indicates buffered I/O with the given value as the buffer size. The lack of or a negative value indicates that the system default buffering scheme should be used.
  • There are also various access modes that you can use while working with open() and file(). Following are those access modes:

r : file Open for read

rU or U : file Open for read with universal NEWLINE support (PEP 278)

w : file Open for write (truncate if necessary)

a : file Open for append (always works from EOF, create if necessary)

r+ : file Open for read and write

w+ : file Open for read and write (see w above)

a+ : file Open for read and write (see a above)

rb : file Open for binary read

wb : file Open for binary write (see w above)

ab : file Open for binary append (see a above)

rb+ : file Open for binary read and write (see r+ above)

wb+ : file Open for binary read and write (see w+ above)

ab+ : file Open for binary read and write (see a+ above)

read(), readline() and readlines() for Input

To understand the above given functions, what we will do is first understand the difference between them conceptually and then take an example for their implementation details and differences.

  • The read() method is used to read number of bytes indicated (in size) directly into a string.

  • The readline() method reads one line of the open file (reads all bytes until a line-terminating character like NEWLINE is encountered).

  • The readlines() method does not return a string like read() and readline() input methods. The readlines() method reads all (remaining) lines and returns them as a list of strings.

We will now take an example to understand these functions with more clarity.

Copy to Clipboard

Output:

Copy to Clipboard

In the above given output, you can see that as initially we used read(10) so only first 10 bytes were printed. In next case, we used readline() first and then we used readline(10) and hence first the complete line was printed and then only 10 bytes were printed. In case of readlines(), all the lines were printed in the form of list as mentioned above. Although you can notice that readlines(2), did not print anything as readlines() requires the size to be passed equivalent to atleast the number of bytes in one line. We will now see how to write to a file.

write and writelines()

As we saw in reading files, instead of three there are only two functions for writing to a file. Let us see both of this functions theoretically.

  • write() has same functionality as read and readline(). It is used to write content of string str in file associated with fileObject.

  • The writelines() method operates on a list just like readlines(), but takes a list of strings and writes them out to a file. Line termination characters are not inserted between each line, so if desired, they must be added to the end of each line before writelines() is called.

  • sequence is the list of string sequence and str is the string to be written.
  • There is no writeline() function.

Let us take an example on how to write into a file. For this example, we are considering a text file named “demo.txt” with contents displayed below.

Copy to Clipboard

Here is the code for writing to a file named demo.txt.

Copy to Clipboard

Following is the output of the above code:

Copy to Clipboard

Following is the demo.txt file after running the sample code:

Copy to Clipboard

Going through the comments of the sample code, you will be easily able to understand the running of the program. Moreover, this will also clear all the necessary fundamentals of write and writelines.

Now, we will also have an overview of some other functions which would be helpful in working with files.

seek()

The seek() method (analogous to the fseek() function in C) moves the file pointer to different positions within the file.

Syntax : fileObject.seek(offset[, whence])

  • offset — offset specifies position of the read/write pointer within the file.
  • whence — It is optional parameter and it’s default value is 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.

tell()

It is a complementary method to seek(); it tells you the current location of the file in bytes from the beginning of the file.

close()

It completes the access to file by closing it.

fileno()

It passes back the file descriptor to the open file.

flush()

It will cause the contents of the internal buffer to be written (or flushed) to the file immediately.

isatty()

It is a Boolean built-in method that returns true if the file is a tty-like device and False otherwise.

truncate()

It truncates the file to the size at the current file position or the given size in bytes.

So that’s all about working with files in python. Hope, you guys are enjoying reading my posts, in next post we will start with the sequences (String, List, Tuple and Dictionary) of Python.