<jupyter_start><jupyter_text>File Handling  Write a Python program to read an entire text file.<jupyter_code>file = open('demo.txt')
file_read = file.read()
file_read<jupyter_output><empty_output><jupyter_text>Write a Python program to read first n lines of a file.<jupyter_code>N = 5
with open("demo.txt", "r") as file: 
    for i in range(N):
        line = next(file).strip()
        print(line)<jupyter_output>hi
hello

hellow world
python<jupyter_text>Write a Python program to append text to a file and display the text.<jupyter_code>def Appendtext(fname):
    with open(fname,'a+') as f:
        f.write('appending line 1,\n ')
        f.write('appending line 2. ')
    f.close()
# y=open('file1.txt')
# print(y.read())
Appendtext('demo.txt')

x= open('demo.txt')
print(x.read())<jupyter_output>hi
hello

hellow world
python

python for data sceine
 gts
global technology
hi
bye
file
text file
appending line 1, appending line 2. appending line 1,
 appending line 2.<jupyter_text>Write a Python program to read last n lines of a file.<jupyter_code>def read_lastnlines(fname,n):
    with open('demo.txt') as f:
        for line in (f.readlines() [-n:]):
            print(line)

read_lastnlines('demo.txt',3)<jupyter_output>text file

appending line 1, appending line 2. appending line 1,

 appending line 2.<jupyter_text>Write a Python program to read a file line by line and store it into a list.<jupyter_code>with open("demo.txt") as f:
    lst = f.readlines()
lst = [x.strip() for x in lst] 
lst<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11661237785016286, 'fraction_numerical': 0.008469055374592834, 'mean_word_length': 4.260273972602739, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '666905', 'license': 'MIT', 'n_tokens_mistral': 561, 'n_tokens_neox': 544, 'n_words': 167, 'path': 'Pro Python Day-3_File_handling.ipynb', 'repo_name': 'ratnasankeerthanreddy/Introduction-to-Python', 'size': '1535'}