File input/output

Flat file: a sequence of bytes stored under a filename, containing records that have no structured interrelationship. The term is frequently used to describe a text document from which all word processing or other structure characters or markup have been removed.

Before reading or writing a file, you need to open it:

fileobj=open(filename, mode)

• fileobj is the file object returned by open()
• filename is the string name of the file
• mode is a string indicating the file’s type and what you want to do with it

The first letter of mode indicates the operation:

• r means read.
• w means write. If the file doesn’t exist, it’s created. If the file does exist, it’s overwritten.
• x means write, but only if the file does not already exist.
• a means append (write after the end) if the file exists.

The second letter of mode is the file’s type:

• t (or nothing) means text.
• b means binary.

 

Read() readline() readlines()

The method read() reads at most size bytes from the file. If the read hits EOF before obtaining size bytes, then it reads only available bytes.

Syntax

Following is the syntax for read() method:

fileObject.read( size );
  • size — This is the number of bytes to be read from the file.

You can call read() with no arguments to load the entire file at once. Be careful when doing this with large files; a gigabyte file will consume a gigabyte of memory. 

Return Value

This method returns the bytes read in string.

Example

The following example shows the usage of read() method.

The foo.txt file contains the following lines:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

The py file contain:

#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

line = fo.read(10) # read 10 bytes from the file.
print "Read Line: %s" % (line)

# Close opend file
fo.close()

When we run the above program, it produces following result:

Name of the file:  foo.txt
Read Line: This is 1s

Next we will use another way to read the file 100 characters by 100 characters:

poem=''
fo = open('foo.txt', 'rt' )
chunk = 100
while True:
    fragment = fo.read(chunk)
    if not fragment:
        break
    poem += fragment

fo.close()
print(poem)
Readline()

This function read one line at a time, even a blank line counts and has a length of one.

poem=''

fo=open('relativity','rt')

while True:

    line=fo.readline()

    print('This line has: %s'%line)

    if not line:

        break

    poem+=line

fo.close()

print(poem)

 

Readlines()

The read lines() call reads a line at a time, and returns a list of one-line strings

fo=open('relativity', 'rt')

lines=fo.readlines()
print(len(lines),' lines are read')
for line in lines:

    sentences+=line

    print('This line is :%s' %line)


fo.close()

print(sentences)
Iterator

The easiest way to read a text file is by using a iterator, which returns a line at a time.

fo=open('relativity', 'rt')

for line in fo:
    poem+=line
    
    print('This line has:%s' %lined)
print(poem)
Read a Binary File with read()

This one is simple; all you need to do is just open with ‘rb’:

>>> fin = open('bfile', 'rb')
>>> bdata = fin.read()
>>> len(bdata)
256
>>> fin.close()

 

 

Write()

The write() function returns the number of bytes written. It does not add any spaces or newlines, as print() does.

To add a space and the end of the print staff and start a new line, you can add two argument:

• sep (separator, which defaults to a space, ‘ ‘)
• end (end string, which defaults to a newline, ‘\n’)

print(poem,sep='',end='\n')

First give the value to a variable:

 >>> poem = '''There was a young lady named Bright,
 ... Whose speed was far faster than light;
 ... She started one day
 ... In a relative way,
 ... And returned on the previous night.'''
 >>> len(poem)
 150

Then create a file and write the variable to the file:
The following code writes the entire poem to the file ‘relativity’ in one call:

 >>> fout = open('relativity', 'wt')
 >>> fout.write(poem)
 150
 >>> fout.close()

Or we can write chunks of data ( 50 byte by 50 byte) until the source is done:

fout = open('relativity', 'wt')
size = len(poem)
offset = 0
chunk = 50
while True:
    if offset > size:
    break
    fout.write(poem[offset:offset+chunk])
    offset += chunk
fout.close()
Close files automatically by using with

If you forget to close a file that you’ve opened, it will be closed by Python after it’s no longer referenced. This means that if you open a file within a function and don’t close it explicitly, it will be closed automatically when the function ends.

But you might have opened the file in a long-running function or the main section of the program. The file should be closed to force any remaining writes to be completed.

Python has context managers to clean up things such as open files. You use the form:

with expression as variable:
     block_of_code
>>> with open('relativity', 'wt') as fout:
... fout.write(poem)
...

 After the block of code under the context manager completes (normally or by a raised exception), the file is closed automatically.

 

Change position with seek()

Python keeps track of where you are in the file.

The tell() function returns your current offset from the beginning of the file, in bytes.

The seek() function lets you jump to another byte offset in the file. seek() also returns the current offset.

You can call seek() with a second argument origin: seek( offset, origin ):

• If origin is 0 (the default), go offset bytes from the start. 
• If origin is 1, go offset bytes from the current position.
• If origin is 2, go offset bytes relative to the end

In the os module:

  • you can get by os.SEEK_SET , result 0.
  •  by os.SEEK_CUR, result 1
  • By os.SEEK_END, result 2