# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# # File Handling

# ### Write a Python program to read an entire text file.

file = open('demo.txt')
file_read = file.read()
file_read

# ### Write a Python program to read first n lines of a file.

N = 5
with open("demo.txt", "r") as file: 
    for i in range(N):
        line = next(file).strip()
        print(line)


# ### Write a Python program to append text to a file and display the text.

# +
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())


# -

# ### Write a Python program to read last n lines of a file.

# +
def read_lastnlines(fname,n):
    with open('demo.txt') as f:
        for line in (f.readlines() [-n:]):
            print(line)

read_lastnlines('demo.txt',3)
# -

# ### Write a Python program to read a file line by line and store it into a list.

with open("demo.txt") as f:
    lst = f.readlines()
lst = [x.strip() for x in lst] 
lst

#

StarcoderdataJupyterScriptsDedupFiltered