TOPIC: Python File Functions and File Modes Uses
Python File Functions:
1. read()
2. readline()
3. readlines()
4. write()
5. writelines()
6. seek()
7. tell() etc.
Reading function:
Python offers three primary methods for reading files: read(), readline() and readlines(). These
functions are
used to access the contents of a file that has been opened for reading.
read() function:
The read() function reads the entire content of the file and returns it as a single string. It's
suitable for situations where we need the entire file content as a single string. Example:
readline() function:
The readline() function reads a single line from a file, allowing you to process files line by line.
It returns each line as a string.
Example of using readline() to read lines from a File:
readlines() function:
The readlines() function reads the file line by line and returns a list of strings, with each string
representing a line. It's commonly used for processing text files with multiple lines of data.
Example of using readlines() to read lines from a File:
The read() function can also be used with an argument to specify the number of
characters to read. For example, file.read(100) reads the next 100 characters from the
file.
When using readlines(), we can iterate through the list of lines to process them individually,
making it suitable for reading and processing multiple lines of data in a file.
read(), readline() and readlines() functions have their specific use cases, and the choice
between them depends on whether we need the entire content as a single string or we want to
process the file line by line.
write() function:
The write() function is used to write data to a file that has been opened in write mode ("w") or
append mode ("a"). We can use write() to add text or data to a file. It's important to note that
write() does not automatically add line breaks. If we want to start a new line, we need to include
the newline character \n.
Example of using write() function:
writelines() function:
The writelines() function is used to write multiple lines to a file. It expects a sequence of lines
(a list of strings) as its argument.
Example of using writelines() functions:
seek() function or file positioning function:
The seek() function allows us to change the current position within a file. We can use it to move
the file pointer to a specific byte position.
Example for using seek() function:
tell() function or current file position function:
The tell() function returns the current file position, which is the byte offset from the beginning
of the file. It's useful for tracking the position in the file.
Example for using tell() function:
Code as discussed in the video:
You can copy and run this code