Python : Files


File objects are Python code’s main interface to external files on your computer.

Files are a core type, but they’re something of an oddball—there is no specific literal syntax for creating them. Rather, to create a file object, you call the built-in open function, passing in an external filename and a processing mode as strings. For example, to create a text output file, you would pass in its name and the ‘w’ processing mode string to write data:

>>> f = open('biryani.txt','w') # open file in write mode
>>> type(f)
<type 'file'>

>>> f.write('chicken\n') # write string of bytes to it
>>> f.write('mutton\n')
>>> f.close()  # close to flush output buffers to disk

This creates a file in the current directory and writes text to it (the filename can be a full directory path if you need to access a file elsewhere on your computer).

To read back what you just wrote, reopen the file in ‘r‘ processing mode, for reading text input—this is the default if you omit the mode in the call. Then read the file’s content into a string, and display it. A file’s contents are always a string in your script, regardless of the type of data the file contains:

>>> f = open('biryani.txt') # 'r' is the default processing mode
>>> text = # read entire file into a string
>>> text

>>> print(text)       # print interprets the control characters
>>> f.close()

>>> text.split()       # file content is always a string
['chicken', 'mutton']

Should you choose to append a string, you need to open the file in ‘a‘ppend mode.

>>> f = open('biryani.txt','a') # open file in append processing mode
>>> f.write('egg')              # writes the bytes at the end of file
>>> f.close() 

>>> f = open('biryani.txt')
>>> text =
>>> print(text)
>>> f.close()

File modes

Type-specific Operations
To know all the file operations, run a dir call on any open file and a help on any of the method names that come back:

>>> dir(f)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

>>> help(f.truncate)
Help on built-in function truncate:

    truncate([size]) -&gt; None.  Truncate the file to at most size bytes.

    Size defaults to the current file position, as returned by tell().


About Deepak Devanand

Seeker of knowledge
This entry was posted in Python and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s