<jupyter_start><jupyter_text>File handling  Opening a file *         File handling is an important part of any web application.Python has several functions for                          creating,reading,updating,and deleting files. * To open a file we use open() function.* It takes two paramters :        i. Name of the file to open if both the file and script in same directory else specify the relative path to the file location.        ii.Mode in which file should open.        | Modes | Operations || :- | :- | | w | Opens file for writing , if the file doesn't exist it will create one | r | 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 | x | Create - Creates the specified file, returns an error if the file exists* In addition you can specify if the file should be handled as binary or text mode&emsp;&emsp; t  : Default , Opens file in text mode .b : Opens file in Binary  mode.<jupyter_code>filename = "test.txt"
f = open(filename) # test.txt file exist in the local directory

# the file is opened in read mode which is the default mode
print("Opened file without any error")

f.close() # close the file<jupyter_output>Opened file without any error<jupyter_text>Basic file operations :<jupyter_code>f = open(filename,'wt') # opens the file for writing in text mode(default)

f.write("This is a sample text") # To write we use write() method and provide a string as argument.

print("Writed to the file without any errors")

f.close()<jupyter_output>Writed to the file without any errors<jupyter_text><jupyter_code>f = open(filename,'r') # opens the file for reading

print(f.read()) # we use read() method to read the contents in the file

f.close()<jupyter_output>This is a sample text<jupyter_text>* Now let's add more contents to the file.<jupyter_code>contents = ["This is the first line ","This is the second line ","This is the third line","This is the fourth line"]

f = open(filename,"w") # we need to open the file in write mode for writing

for i in range(len(contents)):
    f.write(contents[i] + '\n')
print("Writed contents to the file Successfully")  
f.close()<jupyter_output>Writed contents to the file Successfully<jupyter_text>* If the file already has some contents then,opening the file in write mode will overwrite content in the existing file.* Let's print the contents in the file.<jupyter_code>f = open(filename,"r")
print(f.readline()) # You can return one line by using the readline() method
print(f.readline()) # By calling readline() two times, you can read the  first two lines:
f.close()<jupyter_output>This is the first line 

This is the second line<jupyter_text>* If we want to add contents to a exisiting file without overwriting ,then we can open the file in append mode .<jupyter_code>moreContents = ["This is the fifith line ","This is the sixth line "]

f = open(filename,'a')

for i in range(len(moreContents)):
    f.write(moreContents[i] + '\n')

print("Writed contents to the file Successfully\n") 

f.close()

print("Printing the contents in the file\n")

f = open(filename,'r')

print(f.read())

f.close()<jupyter_output>Writed contents to the file Successfully

Printing the contents in the file

This is the first line 
This is the second line 
This is the third line
This is the fourth line
This is the fifith line 
This is the sixth line<jupyter_text>More convenient way :&emsp;&emsp;As we know how to open a file in different mode and perform some basic opertaions.The problem with this approach is that we need to manually close the file after we done with the file.Failure to close the file can result in memory leaks and data loss.* To solve this python provides much a more effective way to open a  file using  with  keyword.<jupyter_code>with open(filename,'r') as f:
    print(f.read())<jupyter_output>This is the first line 
This is the second line 
This is the third line
This is the fourth line
This is the fifith line 
This is the sixth line<jupyter_text>* While we using in this way python automatically close the file for us.   * Now we can open a file in binary mode :<jupyter_code>with open(filename,'rb') as f:
    print(f.read())<jupyter_output>b'This is the first line \r\nThis is the second line \r\nThis is the third line\r\nThis is the fourth line\r\nThis is the fifith line \r\nThis is the sixth line \r\n'<jupyter_text>* The output is in the form of byte String. Deleting a file &emsp;&emsp;For deleting the file we will use os.remove() function from os module and specify the path to the file location .<jupyter_code>import os

if(os.path.exists(filename)):
    os.remove(filename)
    print("Successfully removed the file")
else:
    print("No file exist with file name ", filename)<jupyter_output>Successfully removed the file
{'fraction_non_alphanumeric': 0.08008298755186723, 'fraction_numerical': 0.0, 'mean_word_length': 4.286184210526316, 'pattern_counts': {'":': 0, '<': 28, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '362246', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1411, 'n_tokens_neox': 1396, 'n_words': 677, 'path': 'file handling/file-handling.ipynb', 'repo_name': 'aswathyaa/Acharya-Python', 'size': '4820'}