File processing
• Python too supports file handling and allows users to handle files i.e., to read and write files,
• Python treats files as text or binary.
• Each line of a file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character
• first, we have to open that file.
• f = open(filename, mode)
• Where the following mode is supported:
• r: open an existing file for a read operation.
• w: open an existing file for a write operation.
if the file is not present then it creates the file as well.
• a: open an existing file for append operation.
• r+: To read and write data into the file.
The previous data in the file will be overridden.
• w+: To write and read data. It will override existing data.
• a+: To append and read data from the file. It won’t override existing data.
Examples
file = open('[Link]', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
If you need to extract a string that contains all characters in the file then we can use [Link]().
file = open("[Link]", "r")
print ([Link]())
read the first five characters of stored data and return it as a string:
file = open("[Link]", "r")
print ([Link](5))
Let’s see how to create a file and how to write mode works
file = open('[Link]','w')
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
# Python code to illustrate append() mode
file = open('[Link]', 'a')
[Link]("This will add this line")
[Link]()
Using 'with' , this method any files opened will be closed automatically after one is done,
so auto-cleanup
# Python code to illustrate with()
with open("[Link]") as file:
data = [Link]()
# Python code to illustrate split() function
# do something with data with open("[Link]", "r") as file:
with open("[Link]", "w") as f: data = [Link]()
for line in data:
[Link]("Hello World!!!")
word = [Link]()
[Link](0) print (word)
print([Link]())
import os def append_file(filename, text):
def create_file(filename): try:
try: with open(filename, 'a') as f:
[Link](text)
with open(filename, 'w') as f: print("Text appended to file " + filename + " successfully.")
[Link]('Hello, world!\n') except IOError:
print("Error: could not append to file " + filename)
print("File " + filename + " created successfully.")
except IOError: def rename_file(filename, new_filename):
print("Error: could not create file " + filename) try:
[Link](filename, new_filename)
def read_file(filename):
print("File " + filename + " renamed to " + new_filename + "
try: successfully.")
with open(filename, 'r') as f: except IOError:
print("Error: could not rename file " + filename)
contents = [Link]()
print(contents) def delete_file(filename):
except IOError: try:
[Link](filename)
print("Error: could not read file " + filename) print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
seek() method
• In Python, seek() function is used to change the position of the File Handle to a given specific position.
File handle is like a cursor, which defines from where the data has to be read or written in the file.
• Syntax: [Link](offset, from_what), where f is file pointer
• Parameters:
• Offset: Number of positions to move forward
• from_what: It defines point of reference.
• Returns: Return the new absolute position.
• Change the current file position to 4, (from beggining and return the rest of the line:
• f = open(“[Link]", "r")
[Link](4) OR [Link](4,0)
print([Link]())
• Change the current file position to 4, from end, and return the rest of the line:
• f = open(“[Link]", "r")
[Link](-4,2)
print([Link]())
if __name__ == '__main__':
filename = "[Link]"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filenam
• Go through the google class roomcheck this also:
[Link]
Any Query???