#CREATING A FILE
f=open("f:\student.txt","w")
f.write("This is my first program")
f.close()
# APPEND CONTENTS INTO A FILE
f=open("f:\student.txt","a")
f.write("This data is appended in the program")
f.close()
#READING THE CONTENTS OF A FILE
f=open("f:\student.txt","r")
print(f.read())
f.close()
#REMOVE THE FILE
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
#REMOVE THE DIRECTORY
import os
os.rmdir("f:\johith")
#COPY THE CONTENTS OF ONE FILE INTO ANOTHER
import os
if os.path.exists("f:\student.txt"):
f1=open("f:\student.txt","r")
f2=open("f:\student3.txt","w")
f2.write(f1.read())
f1.close()
f2.close()
else:
print("No such file exists")
# SPLIT THE CONTENTS OF A INTO WORDS
with open("f:\student.txt", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
#read() , tell() and seek() functions
f1 = open("f:\student.txt", "r+")
str = f1.read(10)
print("Read String is : ", str)
position = f1.tell()
print("Current file position : ", position)
position = f1.seek(0, 0);
str = f1.read(10)
print("Again read String is : ", str)
f1.close()
#EXCEPTION HANDLING IN FILES
try:
f = open("f:\myfile.txt", "w")
f.write("This is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
print("Written content in the file successfully")
f.close()
Comments
Post a Comment