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 = f.read() # read entire file into a string >>> text 'chicken\nmutton\n' >>> print(text) # print interprets the control characters chicken mutton >>> 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 = f.read() >>> print(text) chicken mutton egg >>> f.close()
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(...) truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().