📖 generic · 12th TN - English Medium · COMPUTER SCIENCE · Page 230question

PYTHON AND CSV FILES · Part 6

Chapter 2: 3 · COMPUTER SCIENCE

open('c:\pyprg\ch13sample5.csv') # specifying full path You can specify the mode while opening a file. In mode, you can specify whether you want to read 'r', write 'w' or append 'a' to the file. you can also specify “text or binary” in which the file is to be opened. The default is reading in text mode.

In this mode, while reading from the file the data would be in the format of strings. On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files. Python File Modes Mode Description 'r' Open a file for reading. (default) 'w' Open a file for writing.

Creates a new file if it does not exist or truncates the file if it exists. 'x' Open a file for exclusive creation. If the file already exists, the operation fails. 12th Computer Chapter - - 'a' Open for appending at the end of the file without truncating it.

Creates a new file if it does not exist. 't' Open in text mode. (default) ' b' Open in binary mode. '+' Open a file for updating (reading and writing) f= open("sample.txt") #equivalent to 'r' or 'rt' f = open("sample.txt",'w') # write in text mode f = open("image1.bmp",'r+b') # read and write in binary mode Python has a garbage collector to clean up unreferenced objects but, one must not rely on it to close the file.

f = open("test.txt") # since no mode is specified the default mode rt is used # perform file operations f.close() The above method is not entirely safe. If an exception occurs when you are performing some operation with the file, the code exits without closing the file. The best way to do this is using the “with” statement. This ensures that the file is closed when the block inside with is exited.

You need not to explicitly call the close() method. It is done internally. with open("test.txt",’r’) as f: # f is file object to perform file operations Closing a file will free up the

Related topics

Have a question about this topic?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →