Python - Data Type Files

Introduction

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:

Demo

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  w w w .  j  a v a  2s.co  m

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:

Demo

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 .ja  v a2s  .  c o m

Result

Files provide an iterator that automatically reads line by line in for loops and other contexts:

Demo

for line in open('data.txt'): print(line)

Result

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... 

Related Topics