Neeraj Kumar (2201920100191) Python Ppt
Neeraj Kumar (2201920100191) Python Ppt
• File handling can also be used for creating a file. Even files with different extensions
like .pdf, .txt, .jpeg can be created using file handling in Python. To create a file, the file
must be open for writing. To open a file for writing access mode of file must
be w, a, w+, a+. Access modes govern the type of operations possible in the
opened file. It refers to how the file will be used once it’s opened.
• Code:
OPENING A FILE
• Opening a file refers to getting the file ready either for reading or for writing. This
can be done using the open() function. This function returns a file object and takes
two arguments, one that accepts the file name and another that accepts the
mode(Access Mode)
• Syntax: f=open(filename, mode)
• Code:
•
CLOSING A FILE
• close() function closes the file and frees the memory space acquired by that file. It
is used at the time when the file is no longer needed or if it is to be opened in a
different file mode.
• Syntax: File_object.close()
• Code:
WRITING TO FILE
There are two ways to write in a file.
• write() : Inserts the string str1 in a single line in the text file.
Syntax: File_object.write(str1)
• writelines() : For a list of string elements, each string is inserted in the text file.
Used to insert multiple strings at a single time.
Syntax: File_object.writelines(L) for L = [str1, str2, str3]
Code: Output:
READING FROM A FILE
There are three ways to read data from a text file.
• read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.
Syntax: File_object.read([n])
• readline() : Reads a line of the file and returns in form of a string.For specified n, reads
at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.
Syntax: File_object.readline([n])
• readlines() : Reads all the lines and return them as each line a string element in a list.
Syntax: File_object.readlines()
READING FROM A FILE
CODE: OUTPUT:
APPENDING TO A FILE
• When the file is opened in append mode, the handle is positioned at the end of the
file. The data being written will be inserted at the end, after the existing data. Let’s
see the below example to clarify the difference between write mode and append
mode.
Code: Output:
DELETING A FILE
Methods to delete a file using python:
1. Python Delete File using os. remove
2. Delete file in Python using the send2trash module
3. Python Delete File using os.rmdir
Code:
THANK YOU