Site icon DataFlair

How to Write and Read Data From File in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# Program for File in python
try:
    f=open("d://filedata/student.txt","w")
    if(f.writable()):
        mystr=input("Enter  a String: ")
        f.write(mystr)
        print("File Created......")
except FileExistsError as obj:
    print(obj)    
except FileNotFoundError as obj:
    print(obj)    
finally:
    f.close()    

    # print(f.name)
    # print(f.closed)
    # print(f.mode)
    # print(f.writable())
    # print(f.readable())

Program 2

# Program for File in python for read data
try:
    f=open("d://filedata/student.txt","r")
    if(f.readable()):
        while True:
            ch=f.read(1)
            if not ch:
                break
            print(ch,end="")   
except FileNotFoundError as obj:
    print(obj)   
finally:
    f.close()

 

Exit mobile version