Professional Documents
Culture Documents
1
Prepared By:
Sudipta Baladhikary
Computer Science Department
Hariyana Vidya Mandir
• Example – word processor create document files, databases creates files of information.
• Python allow users to handle files i.e., to read and write files, and many other operation.
2
HVM COMPUTER SCIENCE 15-06-2020 Day 6
Data Files • Stores information in ASCII or UNICODE
characters
• Each line of text is terminated/ delimited with EOL
Text character
• By default EOL is newline or carriage return
• Translation required when EOL is read or written
Binary •
•
No delimiter required
No translation required
• Faster
3
HVM COMPUTER SCIENCE 15-06-2020 Day 6
Operations on Files
Reading data from files
csfile=open(“d:\\class_xii\\python.txt”, “w”)
5
HVM COMPUTER SCIENCE 15-06-2020 Day 6
OPENING A FILE:
• open() function is creates a file object/ file handle which serves as a link to the file
• First parameter i.e. file name is a path to the file you want to open.
• Second parameter i.e. mode of file ( read “r”, write “w” or append “a”)
6
HVM COMPUTER SCIENCE 15-06-2020 Day 6
FILE OBJECT / FILE HANDLE:
• File object is a reference to a file on a disk.
7
HVM COMPUTER SCIENCE 15-06-2020 Day 6
FILE MODES:
Sr.No Text File Description Binary
. Mode File Mode
1 r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default rb
mode.
2 w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file wb
for writing.
3 a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the ab
append mode. If the file does not exist, it creates a new file for writing.
4 r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+
r+b
5 w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not wb+
exist, creates a new file for reading and writing
w+b
6 a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The ab+
file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
a+b
8
HVM COMPUTER SCIENCE 15-06-2020 Day 6
9