0% found this document useful (0 votes)
6 views27 pages

kashish cs (3)

Uploaded by

KASHISH MADAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views27 pages

kashish cs (3)

Uploaded by

KASHISH MADAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

FILE HANDLING

# A PYTHON PROGRAM TO READ FIRST 50 BYTES FROM


TEXT FILE

myfile=open(r'C:\Users\dell\Desktop\data.txt')

str=myfile.read(50)

print(str)
# A PYTHON PROGRAM TO READ ENTIRE TEXT FILE

myfile=open(r'C:\Users\dell\Desktop\data.txt')

str=myfile.read()

print(str)
# A PYTHON PROGRAM TO READ FIRST N LINES OF A
FILE

a_file = open("data.txt")

number_of_lines = 3

for i in range(number_of_lines):

line = a_file.readline()

print(line)
# A PYTHON PROGRAM TO APPEND CONTENTS OF ONE
FILE TO ANOTHER FILE-

ifile=open(r'C:\Users\dell\Desktop\data.txt',"r")
outfile=open("km.txt","w")
lines=ifile.readlines()
outfile.writelines(lines)
ifile.close()
outfile.close()
# A PYTHON PROGRAM TO READ A FILE LINE BY LINE
AND STORE IT INTO A LIST.

file=open(r'C:\Users\dell\Desktop\data.txt')
list=file.readlines()
print(list)
#A PYTHON PROGRAM TO READ A FILE LINE BY LINE
AND STORE IT IN A VARIABLE

file=open(r'C:\Users\dell\Desktop\data.txt')
data=file.readlines()
print(data)
# A PYTHON PROGRAM TO READ A FILE LINE BY LINE
STORE IT INTO AN ARRAY

file=open(r'C:\Users\dell\Desktop\file.txt')
content_array = []
for line in file:
content_array.append(line)
print(content_array)
# WRITE A PYTHON PROGRAM TO FIND THE LONGEST
WORDS

def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) ==
max_len]

print(longest_word('data.txt'))
#A PYTHON PROGRAM TO COUNT THE NUMBER OF
LINES IN TEXT FILE
def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print("Number of lines in the file:
",file_lengthy("data.txt"))
# A PYTHON PROGRAM TO COUNT THE FREQUENCY OF
WORDS

from collections import Counter


def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())

print("Number of words in the


file :",word_count("data.txt"))
# A PYTHON PROGRAM TO WRITE A LIST TO A FILE.

color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']


with open('data.txt', "w") as myfile:
for c in color:
myfile.write("%s\n" % c)

content = open('data.txt')
print(content.read())
# A PYTHON PROGRAM TO COMBINE EACH
LINE FROM FIRST FILE WITH THE
CORRESPONDING LINE IN SECOND FILE. .

with open('data.txt') as fh1, open('km.txt') as fh2:


for line1, line2 in zip(fh1, fh2):

print(line1+line2)
# A PYTHON PROGRAM TO READ A RANDOM LINE
FROM A FILE.
import random
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line('data.txt'))
#A PYTHON PROGRAM TO ASSESS IF A FILE IS CLOSED
OR NOT

f = open('data.txt','r')
print(f.closed)
f.close()
print(f.closed)
# A PYTHON PROGRAMS TO REMOVE NEWLINE
CHARACTERS FROM FILE

def remove_newlines(fname):
flist = open(fname).readlines()
return [s.rstrip('\n') for s in flist]

print(remove_newlines("data.txt"))
# A PYTHON PROGRAM THAT TAKES A TEXT FILE AS
INPUT AND RETURNS THE NUMBER OF WORDS OF A
GIVEN TEXT FILE.

def count_words(filepath):
with open(filepath) as f:
data = f.read()
data.replace(",", " ")
return len(data.split(" "))
print(count_words("words.txt"))
# A PYTHON PROGRAM TO EXTRACT CHARACTERS
FROM VARIOUS FILES AND PUT THEM IN TO LIST
import glob
char_list = []
files_list = glob.glob("*.txt")
for file_elem in files_list:
with open(file_elem, "r") as f:
char_list.append(f.read())
print(char_list)
# A PYTHON PROGRAM TO GENERATE 26 TEXT FILES
NAMED A.TXT, B.TXT, AND SO ON UP TO Z.TXT
import string, os
if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_uppercase:
with open(letter + ".txt", "w") as f:
f.writelines(letter)
#A PROGRAM TO ENTER THE INTEGER VALUE USING
PICKLE
import pickle
file=open(r'C:\Users\dell\Desktop\binary.dat','wb')
while True:
value=int(input("Enter integer value"))
pickle.dump(value,file)
choice=input("Do you want to add more data Y/N")
if choice=='N':break
file.close()
# A PYTHON PROGRAM TO WRITE CONTENTS OF FILE IN
ANOTHER FILE BY READING FIRST FILE WRITING IN
ANOTHER
import pickle
file=open(r'C:\Users\dell\Desktop\BinaryFile.dat','rb')
outfile=open(r'C:\Users\dell\Desktop\
BinaryFile2.dat','wb')
try:
while True:
l=pickle.load(file)
print(l)
pickle.dump(l,outfile)
except EOFError:
pass
file.close()
outfile.close()
# A PYTHON PROGRAM TO PRINT WORDS CONTAINING
DIGITS

file=open("data.txt")
for line in file.readlines():
words=line.split()
print(words)
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter)
# A PYTHON PROGRAM TO PRINT THE LETTERS
STARTING WITH A OR a
def countlines():
file=open("data.txt")
lines=file.readlines()
count=0
for w in lines:
if w[1]=="A" or w[1]=="a":
count=count+1
print("Total lines started with A or a",count)
file.close()
countlines()
#A PYTHON PROGRAM USING BINARY FILE
import pickle

def writeme():

f=open("binary1.dat","wb")

rec=[]

while True:

rno=int(input("enter rollno"))

nm=input("enter name")

marks=int(input("enter marks"))

data=[rno,nm,marks]

rec.append(data)

ch1=input("u want to continue")

if ch1=='n':

break

pickle.dump(rec,f) # write record in a file

f.close()

def readme():

f=open("binary1.dat","rb")

s=pickle.load(f) #reads all records in all togeather

for i in s:

print(i)
f.close()

def searchupdateme():

f=open("binary1.dat","rb+")

s=pickle.load(f)

found=0

rn=int(input("enter to search"))

for i in s:

if i[0]==rn:

print(i)

i[2]=input("enter new marks")

found=1

break

if found==0:

print("not found")

else:

f.seek(0)# bring pointer at first record

pickle.dump(s,f) #write all records all again not only search record ..

f.close()

while True:

print("1. write")
print("2. read")

print("3. search and update ")

print("4. exit")

ch=int(input("enter choice"))

if ch==1:

writeme()

print("records added in file")

elif ch==2:

readme()

elif ch==3:

searchupdateme()

else:

break

You might also like