AI Lab 6 Files
AI Lab 6 Files
Files
Files allow us to work with data, without needing to enter it each time our program runs. Files
also allow us to store results from our program in a more permanent manner.
Python has a built-in open() function to open a file. This function returns a file object, also called
a handle, as it is used to read or modify the file accordingly.
We can specify the mode while opening a file. In mode, we specify whether we want to read r,
write w or append a to the file. We can also specify if we want to open the file in text mode or
binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like images or executable files.
Mode Description
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if
it exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
a Opens a file for appending at the end of the file without truncating it. Creates a new
file if it does not exist.
Unlike other languages, the character a does not imply the number 97 until it is encoded
using ASCII (or other equivalent encodings).
Moreover, the default encoding is platform dependent. In windows, it is cp1252 but utf-8 in
Linux.
So, we must not also rely on the default encoding or else our code will behave differently in
different platforms. Hence, when working with files in text mode, it is highly recommended to
specify the encoding type.
This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
This way, we are guaranteeing that the file is properly closed even if an exception is raised that
causes program flow to stop.
The best way to close a file is by using the with statement. This ensures that the file is closed
when the block inside the with statement is exited.
We don't need to explicitly call the close() method. It is done internally.
In order to write into a file in Python, we need to open it in write w, append a or exclusive
creation x mode.
We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due
to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. This
method returns the number of characters written to the file.
This program will create a new file named test.txt in the current directory if it does not exist. If it
does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the different lines.
We can see that the read() method returns a newline as '\n'. Once the end of the file is reached,
we get an empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
methods return empty values when the end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
readline(n=-1) Reads and returns one line from the file. Reads in at most n
bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at
most n bytes/characters if specified.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified,
resizes to current location.
write(s) Writes the string s to the file and returns the number of
characters written.
1. Create a text file “intro.txt” in python and ask the user to write a single line of text by
user input.
2. Create a text file “MyFile.txt” in python and ask the user to write separate 3 lines with
three input statements from the user.
3. Write a program to read the contents of both the files created in the above programs and
merge the contents into “merge.txt”. Avoid using the close() function to close the files.
4. Find the total occurrences of a specific word from a text file:
5. Write a program to know the cursor position and print the text according to below-given
specifications: