Sunday, 24 December 2023

Python File Handling

File Handling

File handling is an important part of any web application. 
Python provides inbuilt functions for creating, writing, and reading files.
There are two types of files that can be handled in python,normal text
files and binary files.

By using the below modes we can read or write into the files 

There are four different methods (modes) for opening a file: 
"r" - Read - Default value. Opens a file for reading, error if the file does
not exist 
"a" - Append - Opens a file for appending, creates the file if it does not
exist 
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists 
"t" - Text - Default value. Text mode 
"b" - Binary - Binary mode (e.g. images) 

We can perform read and write simultaniously by using the below modes

Read and Write (‘r+’): Open the file for reading and writing. The
handle is positioned at the beginning of the file. Raises I/O error if the
file does not exist. 
Write and Read (‘w+’) : Open the file for reading and writing. For an
existing file, data is truncated and over-written. The handle is
positioned at the beginning of the file. 
Append and Read (‘a+’) : Open the file for reading and writing. The file
is created if it does not exist. The handle is positioned at the end of the
file. The  data being written will be inserted at the end, after the existing
data. 

xb -- create binary
wb -- write binary 
ab -- append binary 
rb -- read binary


file built in functions -- open()
file built in methods -- read()--reads entire file ,readline() -- here we need to give number to read those many charecters,readlines() -- it prints all lines in the form of list. -- all these are for to read
write() -- to write
close() -- to close
seek() -- To change file position 
tell() -- Returns the currentfile position

--Create file example
f = open("C:/Desktop/file.txt", "x")
f.close()  

--To open a file and write
--Write method will delete the old data and writes new data.
f = open("file.txt", "w") 
f.write("hellow")
f.close()
-- Append method
f.append("hellow")
f.close()

By looping through the lines of the file, you can read the whole file, line by line: 
f = open("C:/Desktop/file.txt", "r")
for x in f: 
    print (x)
f.close()


No comments:

Post a Comment

SQL -

 Window Functions -  Window function: pySpark window functions are useful when you want to examine relationships within group of data rather...