(PP-6)

 File read and write operation:

fo=open("file1.txt","w")

line1="Hello this is amit"

line2=" and this is karthik"

fo.write(line1)

fo.write(line2)

fo.close()

fo=open("file1.txt","r")

str=fo.read()

print("the string is:",str)

fo.close()

                OR

f=open("filel.txt", "w") print ("Name of the file:", f.name) print ("closed or not:", f.closed) print("opening mode", f.mode) f.write("hello") f.close() f=open("filel.txt","r+") str=f.read() print("string is:", str) f.close()


Copy one file into another file:

fo=open("file1.txt","r")

file1=fo.read()

fo.close()

f1=open("file2.txt","w")

f1.write(file1)

f1=open("file2.txt","r")

file2=f1.read()

print("the second file content is:",file2)

f1.close()

                    OR
f=open ("file2.txt", "w")
f.write("hello world")
f.close()

f=open ("file2.txt","r")
str=f.read() 
x=str
f.close()

fl=open ("file3.txt", "w")
fl.write(x)
fl.close()


Use of seek() and tell():

fo=open("file1.txt","w")

fo.write("Good Evening\n Python is great programming language \n seek and tell position ")

fo.close()

fo=open("file1.txt","r+")

str1=fo.read(20)

print("Read string is:",str1)

position=fo.tell()

print("Current file position:",position)

position=fo.seek(0,0)

str1=fo.read(10)

print("Again read string is:",str1)

                OR

f=open ("6c.txt", "w") f.write("python programming") f.close() f=open("6c.txt","r") f.seek(6) print (f.tell()) print (f.read()) f.close()



Read first n lines of file:


inputfile=("file1.txt")

N=int(input("Enter no. of file to read from first of file:"))

with open(inputfile, 'r')as filedata:

    lineslist=filedata.readlines()

print("The following are the first ",N," lines of a file:")

for textline in (lineslist[:N]):

    print(textline,end=" ")

filedata.close()

                    or

n=int(input("enter number of first lines to read:")) f=open("pracsp.txt.txt","r") for line in(f.readline()[:n]): print(line,end=" ") f.close()




Appending content to a file:

fo=open("file2.txt","a")

fo.write("\nthis is text for appending")

fo.close()

fo=open("file2.txt","r")

str1=fo.read()

print("the content after appending",str1)

fo.close()



Read last line from a file:

fo=open("file2.txt","w")

fo.write("first line \n second line \n third line")

fo.close()

fo=open("file2.txt","r")

line=fo.readlines()

print(line[-1])

fo.close()


Program to get file descriptor:

fo=open("file13.txt","w")

fo.write("hello")

print("Name of the file:",fo.name)

fid=fo.fileno()

print("File Descriptor:",fid)

fo.close()


Read last n lines from a file:


n=int(input("enter number of last line to read")) f=open("file15.txt","r") for line in(f.readlines()[-n]): print(line,end=" ") f.close

Comments

Popular posts from this blog

python(BI)

Prac_8(AMP)

LSA10