File objects in Python handles external files on your computer.
They can read and write text files, audio clips, Excel documents, saved email messages.
Files are a core type.
To create a file object, call the built-in open function, passing in an external filename and an optional 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('data.txt', 'w') # Make a new file in output mode ('w' is write) f.write('Hello\n') # Write strings of characters to it f.write('world\n') # Return number of items written in Python 3.X f.close() # Close to flush output buffers to disk # from www. j av a 2s. c om
Here, creates a file in the current directory and writes text to it.
The filename can be a full directory path.
To read back what you just wrote, reopen the file in 'r' processing mode.
To read text input, omit the mode.
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('data.txt') # 'r' (read) is the default processing mode text = f.read() # Read entire file into a string print( text ) print(text) # print interprets control characters print( text.split() ) # File content is always a string # from w w w .j a va 2s . c o m
Files provide an iterator that automatically reads line by line in for loops and other contexts:
for line in open('data.txt'): print(line)
Run a dir call on open file and a help on any of the method names for help information:
>>> dir(f) [ ...many names omitted... 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines'] >>>help(f.seek) ...try it and see...