Computer Science TTR
Computer Science TTR
Definitions:
File: A file is a collection of related data stored in a particular area on the
disk.
Stream: It refers to a sequence of bytes. File handling is an important
part of any web application.
Data Files: The data files that store data pertaining to specific
applications, for later use.
Data files can be stored in two ways:
Text Files: Text files are structured as a sequence of lines, where each
line includes a sequence of characters.
Binary Files : A binary file is any type of file that is not a text file.
Text Files:
1. file.read(n): Reads n bytes, if no n is given reads the entire file.
2. file.readline(n): Reads n bytes till it reaches EOF character, if no n
is given reads till end of newline char.
3. file.readlines(): Reads all lines and returns it as a list.
Note: All the read function has ‘\n’ at the end so to access the last
character we need to use [-2]
4. file.seek(offset, from_where): Moves cursor of the file.
From_where:
a. 0: sets the cursor at the beginning of the file.
b. 1: sets the cursor at the current position (only binary).
c. 2: sets the cursor at the end of the file (only binary).
Note: when using seek in binary mode in “2” mode, there are
two characters at the end of a line ‘\r\n’
5. file.tell(): Gives the cursor's current position as an integer.
6. file.write(text): Writes the text to the file.
7. file.writelines(list): Write each sentence in a list.
Note: writelines does not add EOF character so each string in list
must have EOF character at the end.
Binary Files:
import pickle
# Creating A Binary File
def create_file():
file = open("stud.DAT", "wb")
n = int(input("Enter number of entries: "))
for i in range(n):
roll = int(input("Roll No: "))
name = int(input("Name: "))
mark = int(input("Marks: "))
rec = [roll, name, mark]
pickle.dump(rec, file)
file.close()
CSV Files:
import csv
# Note: We use text mode for csv files, also ensure to define
newline as empty
file = open('file.csv', 'w', newline='')
writer = csv.writer(file, delimiter=',', quotechar='"')
writer.writerow(['Abinav', 12, 'C'])
data = [['John', 12, 'A'], ['Doe', 11, 'B']]
writer.writerows(data)
file.close()