Product SiteDocumentation Site

Chapter 10. File handling

10.1. File opening
10.2. Closing a file
10.3. Reading a file
10.4. Writing in a file
10.5. copyfile.py
10.6. Random seeking in a file
10.7. Count spaces, tabs and new lines in a file
A file is some information or data which stays in the computer storage devices. You already know about different kinds of file , like your music files, video files, text files. Python gives you easy ways to manipulate these files. Generally we divide files in two categories, text file and binary file. Text files are simple text where as the binary files contain binary data which is only readable by computer.

10.1. File opening

To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open. Modes are like
"r" -> open read only, you can read the file but can not edit / delete anything inside
"w" -> open with write power, means if the file exists then delete all content and open it to write
"a" -> open in append mode
The default mode is read only, ie if you do not provide any mode it will open the file as read only. Let us open a file

>>> f = open("love.txt")
>>> f
<open file 'love.txt', mode 'r' at 0xb7f2d968>