Python File object

File objects are somewhat special than others:

  1. They don't respond to expression operators;
  2. Only export methods for file-processing tasks ;
  3. Tuples share many(but not all) methods that lists have.

Opening files

The built-in open function returns an file object with below format:

fileobj = open('/path/to/filename',mode)  

modes:

r - open file and read from it
w - open for writing, truncating the file first
a - open file and append to it
add b to above mode to work with binary data
add + opens file for input and output

  • r+ read and write
  • w+ read and write(delete old file before start write)

Refer to python documentation for detail open parameter

Using Files

  • File iterators are the best practice for reading lines
  • Data read from a file always comes back to your script as a string, so you’ll have to convert it to a different type of Python object if a string is not what you need
  • Also need convert any objects to strings before write into file
  • Files are buffered by default. Changes will write to disc when calling close or flush method
  • seek method allows python script jumps into and read from specific location of a file
  • Use close method to release file object is a good habit to form

Files in Action

open, write and read

>>> fileobj=open('newfile.txt','w')
>>> fileobj.write('first line here\n')  # write methods don’t add the end-of-line character for us, so we must include it to properly terminate our lines
minate our lines  
>>> fileobj.close()

>>> fileobj=open('newfile.txt','r')
>>> fileobj.readline()
'first line here\n'  
>>> fileobj.readline()
''  # Empty string: end-of-file  

File iterators

>>> for line in open('newfile.txt'):
...   print(line)
...
first line here  

String Conversions

Write

>>> X, Y, Z = 43, 44, 45                       # Native Python objects
>>> S = 'Spam'                                 # Must be strings to store in file
>>> D = {'a': 1, 'b': 2}
>>> L = [1, 2, 3]
>>>
>>> F = open('datafile.txt', 'w')              # Create output text file
>>> F.write(S + '\n')                          # Terminate lines with \n
>>> F.write('%s,%s,%s\n' % (X, Y, Z))          # Convert numbers to strings
>>> F.write(str(L) + '$' + str(D) + '\n')      # Convert and separate with $
>>> F.close()

Read

>>> F = open('datafile.txt','r')
>>> line = F.readline()
>>> line
'spam\n'  
>>> line.rstrip()   # use rstrip method to get rid of end-of-line character
'spam'  
>>> line = F.readline()
>>> line
'43,44,45\n'  
>>> parts = line.split(',')  # Split (parse) on commas
>>> parts
['43', '44', '45\n']
>>> numbers = [int(P) for P in parts] #Convert to int
>>> numbers
[43, 44, 45]