Python Exercise7

  1. Write a program to read file contents at a time

f = open(‘input.txt’,’r’)

print(f.read())

f.close()

 

  1. Write a program to read a file char by char

f = open(‘input.txt’,’r’)

print(f.read(1))

print(f.read(1))

f.close()

 

  1. Write a program to read a file line by line

f = open(‘input.txt’,’r’)

print(f.readline())

print(f.readline())

f.close()

 

  1. Write a program to read all lines in to a list

f = open(‘input.txt’,’r’)

print(f.read())

f.close()

 

  1. Write a program to write in to a file

f = open(‘input.txt1′,’w’)

f.write(“this is line1”)

f.close()

 

  1. Write a program to append to an existing file

f = open(‘input.txt’,’a’)

f.write(“nthis is newline”)

f.close()

 

  1. Write a program to print nth line and print range of lines

 

f=open(“input.txt”,”r”)

contents=f.readlines()

print(contents[5])                               #prints 6th line

print(contents[6:12])                         #prints from 7th to 11th

f.close()

 

  1. Write a Program to read the file and print

Output:Item: Pens,Quantity: 10,Price: 10.10

Pens,10,10.10

Pencils,20,15.14

Erasers,30,10

Box,10,50

Bags,10,200

 

f=open(“prices.txt”,”r”)                                                                                       #open the file in read mode

for line in f:                                                                                                            #get a line

    fields=line.rstrip().split(‘,’)                                                                             #split the line

    print(“Item: {},Quantity: {},Price: {}”.format(fields[0],fields[1],fields[2]))           #print the 3rd field

f.close()

 

9. Write a program to get all the .txt files from the current working directory

 

import glob

import os

#print( os.getcwd())

files=glob.glob(‘*.txt’)

print (len(files))

print (files)

 

  1. Write a program to print all the lines which does not have ‘smile’

f=open(‘input3.txt’,’r’)

for line in f:

    if “smile”.lower() in line.lower():continue

    print(line)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s