Beruflich Dokumente
Kultur Dokumente
Till now, we were taking the input from the console and writing it back to the console to interact with the user.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large,
and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible
to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every
time. Here, comes the need of file handling.
Let’s take an Example of how normal people will handle the files. If we want to read the data from a file or write
the data into a file, then, first of all, we will open the file or will create a new file if the file does not exist and then
perform the normal read/write operations, save the file and close it.
Similarly, we do the same operations in python using some in-built methods or functions.
All binary files follow a specific format. We can open some binary files in the normal text editor
but we can’t read the content present inside the file. That’s because all the binary files will be
encoded in the binary format, which can be understood only by a computer or machine.
For handling such binary files we need a specific type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise, you need a
pdf reader software to open .pdf binary files and you need a photo editor software to read the
image files and so on.
1.1.2 Text file
Text files don’t have any specific encoding and it can be opened in normal text editor itself.
Here, file_name is the name of the file or the location of the file that you want to open, and
file_name should have the file extension included as well. Which means in test.txt – the term
test is the name of the file and .txt is the extension of the file.
The mode in the open function syntax will tell Python as what operation you want to do on a
file.
1.3.2 File open modes
mode Description
r It opens the file to read-only. The file pointer exists at the beginning. The file
is by default open in this mode if no access mode is passed.
rb It opens the file to read only in binary format. The file pointer exists at the
beginning of the file.
r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.
NOTE:
If we need to read the file first and then write we use this.
Doesn’t do truncate operation on file, so we are not going to lose
file data.
Mostly used to update the file data.
rb+ It opens the file to read and write both in binary format. The file pointer
exists at the beginning of the file.
w It opens the file to write only. It overwrites the file if previously exists or
creates a new one if no file exists with the same name. The file pointer exists
at the beginning of the file.
NOTE:
We use this when we want do fresh write in to the file.
truncates the file, overwriting whatever was already there.
wb It opens the file to write only in binary format. It overwrites the file if it
exists previously or creates a new one if no file exists with the same name.
The file pointer exists at the beginning of the file.
w+ It opens the file to write and read both. It is different from r+ in the sense
that it overwrites the previous file if one exists whereas r+ doesn't overwrite
the previously written file. It creates a new file if no file exists. The file
pointer exists at the beginning of the file.
NOTE:
opens for reading and writing, truncating the file but also allowing
you to read back what's been written to the file.
wb+ It opens the file to write and read both in binary format. The file pointer
exists at the beginning of the file.
a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with
the same name.
NOTE:
appends to the file, adding onto whatever was already there.
ab It opens the file in the append mode in binary format. The pointer exists at
the end of the previously written file. It creates a new file in binary format if
no file exists with the same name.
a+ It opens a file to append and read both. The file pointer remains at the end
of the file if a file exists. It creates a new file if no file exists with the same
name.
NOTE:
opens for appending and reading, allowing you both to append to
the file and also read its contents
It doesn’t to truncate of file.
ab+ It opens a file to append and read both in binary format. The file pointer
remains at the end of the file.
x Exclusive Creation Mode: This mode is used exclusively to create a file. If a file
of the same name already exists, the function call will give error.
x+ reading and writing mode. Similar to w+ as it will create a new file if the file
does not exist. Otherwise, will raise FileExistsError.
Example:
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
There are three ways in which we can read the files in python.
read([n])
readline([n])
readlines()
Here, n is the number of bytes to be read.
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Here we have not provided any argument inside the read() function. Hence it will read all the content
present inside the file.
Output:
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
This function returns the first 2 characters of the next line.
Output:
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Using this function we can read the content of the file on a line by line basis.
Output:
Example 5:
Output:
Output:
Output:
Here we are opening the file test.txt in a read-only mode and are reading only the first 5 characters of
the file using the my_file.read(5) method.
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites the content present
inside the file that you are writing, and all the previous data will be erased.
We have two methods for writing data into a file as shown below.
write(string)
writelines(list)
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’ file.
Output:
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
The first line will be ‘Hello World’ and as we have mentioned \n character, the cursor will move
to the next line of the file and then write ‘Hello Python’.
Remember if we don’t mention \n character, then the data will be written continuously in the
text file like ‘Hello WorldHelloPython’
Output:
Example 3:
fruits = [“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”]
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously.
Output:
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file.
Output:
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new line.
Output:
Example 3:
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)
The above code appends a list of data into a ‘test.txt’ file.
Output:
Example 4:
text=["\nHello","\nHi","\nPython"]
my_file=open("C:/Documents/Python/test.txt",mode="a+")
my_file.writelines(text)
print("where the file cursor is:",my_file.tell())
my_file.seek(0)
for line in my_file:
print(line)
In the above code, we are appending the list of data into the ‘test.txt’ file. Here, you can observe that
we have used the tell() method which prints where the cursor is currently at.
Output:
1.4.4 Python Close File
Once all the operations are done on the file, we must close it through our python script using
the close() method. Any unwritten information gets destroyed once the close() method is called
on a file object.
We can perform any operation on the file externally in the file system is the file is opened in
python, hence it is good practice to close the file once all the operations are done.
fileobject.close()
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
my_file.close()
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
my_file.close()
1.4.5 Examples of r+ and w+ mode
with open('somefile.txt', 'w+') as f:
# Note that f has now been truncated to 0 bytes, so you'll only
# be able to read data that you write after this point
f.write('somedata\n')
f.seek(0) # Important: return to the top of the file before reading, otherwise you'll just read an empty string
data = f.read() # Returns 'somedata\n'
Syntax:
file.seek(offset[, from])
If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the current position.
If from is 2, then the end of the file would serve as the reference position.
Note that if the file is opened for appending (mode ‘a’ or ‘a+’), any seek() operations will be
undone at the next write. If the file is only opened for writing in append mode (mode ‘a’), this
method is essentially a no-op, but it remains useful for files opened in append mode with
reading enabled (mode ‘a+’). If the file is opened in text mode (without ‘b’), only offsets
returned by tell() are legal. Use of other offsets causes undefined behavior.
Note that not all file objects are seekable.
1.4.9 Conclusion:
X and X+ mode:
x x+
Read ✘ ✔
Write ✔ ✔
Creates file ✔ ✔
Erases file ✘ ✘
Initial position Start Start
1.5 The file Object Attributes and functions
Once a file is opened and you have one file object, you can get various information related to that
file.
1.5.1 list of all attributes on file object
Sr.No. Attribute & Description
1
file.closed
Returns true if file is closed, false otherwise.
2
file.mode
Returns access mode with which file was opened.
3
file.name
Returns name of the file.
4
file.softspace
Returns false if space explicitly required with print, true otherwise.
detach(self, /)
Separate the underlying buffer from the TextIOBase and return it.
fileno(self, /)
Returns underlying file descriptor if one exists.
flush(self, /)
Flush write buffers, if applicable.
isatty(self, /)
Return whether this is an 'interactive' stream.
read(self, size=-1, /)
Read at most n characters from stream.
readline(self, size=-1, /)
Read until newline or EOF.
Change the stream position to the given byte offset. The offset is
interpreted relative to the position indicated by whence. Values
for whence are:
seekable(self, /)
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError.
This method may need to do a test seek().
tell(self, /)
Return current stream position.
truncate(self, pos=None, /)
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO
position as reported by tell(). Returns the new size.
writable(self, /)
Return whether object was opened for writing.
If False, write() will raise OSError.
write(self, text, /)
Write string to stream.
Returns the number of characters written (which is always equal to
the length of the string).