8.4 File Handling
8.4 File Handling
File handling in Python is a powerful and versatile tool that can be used to perform a wide range
of operations. However, it is important to carefully consider the advantages and disadvantages of
file handling when writing Python programs, to ensure that the code is secure, reliable, and
performs well.
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in the file then we
can use file.read().
Example 3: In this example, we will see how we can read a file using the with statement.
print(data)
Example 4: Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and return it as a
string:
Output:
Hello
Example 5:
We can also split lines while reading files in Python. The split() function splits the variable when
space is encountered. You can also split using any characters as you wish.
# Python code to illustrate split() function
with open("geeks.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Output:
Example 2: We can also use the written statement along with the with() function.
Output:
Hello World!!!
Output:
This is the write command. It allows us to write in a particular file. This will add this line.