File is a named location on disk to store related Closing a file
information. It is used to permanently store data When we are done with
in a non-volatile memory (e.g. hard disk). operations to the file, we Since, random access memory (RAM) is volatile need to properly close which loses its data when computer is turned the file. off, we use files for future use of the data. Closing a file will free up When we want to read from or write to a file we the resources that were need to open it first. When we are done, it needs tied with the file and is to be closed, so that resources that are tied with done using Python the file are freed. close() method. Hence, in Python, a file operation takes place Python has a garbage in the following order. collector to clean up Open a file unreferenced objects but, we must not rely on it to Read or write (perform operation) close the file. Close the file f = open("test.txt") Opening a file # perform file operations Python has a built-in function f.close() Writing the file open() to open a In order to write into a file in Python, with open("test.txt",'w') as f: file. This we need to open it in write 'w', f.write("my first file\n") function returns append 'a' or exclusive creation 'x' a file object, also mode. f.write("This file\n\n") called a handle, We need to be careful with the 'w' mode f.write("contains three as it is used to as it will overwrite into the file if it already exists. All previous data are lines\n") read or modify the file erased. Python file modes
accordingly. Writing a string or sequence of bytes
>>> f = (for binary files) is done using write() open("test.txt") method. This method returns the We can specify number of characters written to the the mode while file. File writing methods writable() opening a file. In mode, we Returns True if the file stream can specify whether be written to. we want to read write(s) 'r', write 'w' or Write string s to the file and return append 'a' to the the number of characters written. file. writelines(lines) We also specify if Write a list of lines to the file. we want to open Sample File copy operation the file in text mode or binary mode. The default is reading in text mode. Reading functions read(n) Examples Read atmost n characters f = open("test.txt") form the file. Reads till end # equivalent to 'r' or 'rt' of file if it is negative or f = open("test.txt",'w') None. # write in text mode readable() f= Returns True if the file open("img.bmp",'r+b') stream can be read from. # read and write in readline(n=-1) binary mode Read and return one line f= from the file. Reads in at open("test.txt",mode = most n bytes if specified. 'r',encoding = 'utf-8') readlines(n=-1) # Specfied with Read and return a list of encoding lines from the file. Reads in at most n bytes/characters if specified.
Michael Bazzell - Open Source Intelligence Techniques - Resources For Searching and Analyzing Online Information-Createspace Independent Publishing Platform (2021)