Reading and writing files in Data File handling
Hi guys today we are going to see about the sample program to reading and writing files in Data File handling
1.Write a program to display the size of a file in bytes.
myfile = open(r'E: \poem. txt', "r")
str = myfile.read()
size = len(str) print("Size of the given file poem. txt is")
print (size, "bytes")
2.Write a program to display the number of lines in the file.
myfile = open(r'E: \poem.txt", "r")
s = myfile.readlines ()
linecount = len(s)
print("Number of lines in poem. txt is", linecount)
myfile.close()
3.Create a file to hold some data, separated as lines
fileout= open("Student1.txt", "w")
for i in range(5):
name = input ("Enter name of student :")
fileout.write(name)
fileout.write('\n') +
fileout.close()
4.Reading a file's first three lines - line by line
myfile = open(r'E: \poem.txt', "r")
str = myfile.readline()
print (str, end = ' ') str = myfile.readline()
print (str, end = '')
str = myfile.readline()
print (str, end = ' ')
myfile.close()