Tuesday, March 15, 2016

Reading and Writing Files in Python

File Types

A file can be either text or binary.
A text file is  a sequence of lines and a line is a sequence of characters.
The line is terminated by a EOL (End Of Line) character. 

A binary file is any file. Binary files can only be processed if we know the file structure.

Open ( )

open() returns a file object
file_object = open(filename, mode) 
mode  is way the file will be used.

Mode

'r' when the file will only be read

'w' for only writing (an existing file with the same name will be erased)

'a' opens the file for appending; any data written to the file is automatically
added to the end. 

'r+' opens the file for both reading and writing.
>>> f = open('workfile', 'w')
>>> print f

Create a text file

file = open("newfile.txt", "w")
file.write("hello python")
file.write("and another line")
file.close()

How to read a text file

file = open('newfile.txt', 'r')
print file.read()
Output:
hello world in the new file
and another line
We can also specify how many characters the string should return, by using
file.read(n), where "n" determines number of characters.
file = open('newfile.txt', 'r')
print file.read(5) 
Output:
hello

file.readline( )

The readline() function will read from a file line by line (rather than pulling
the entire file in at once).
file = open('newfile.txt', 'r')
print file.readline():
Output:
hello python

file.readlines( )

readlines() returns the complete file as list of strings 
file = open('newfile.txt', 'r')
print file.readlines()
Output:
['hello python', 'and another line']

Looping over a file object

file = open('newfile.txt', 'r')

for line in file:
    print line,
Output:

hello python
and another line

file.write( )

The write method takes one parameter, which is the string to be written. 

To start a new line after writing the data, add a 
 character to the end.
file = open("newfile.txt", "w")
file.write("This is python")
file.write("And here is another line")
file.close()

Close ( )

When you’re done with a file, call f.close() to close it and free up any system
resources taken up by the open file. 


Python code Answer for A/L ICT 2015 Structured Question

file = open("marks.txt", "a")
running=1
while (running ==1) :
    indexNo = raw_input("Enter Index No: ") 
    if (indexNo=="-1"):
        running=-1
    else :
        mark1 = raw_input("Enter marks 1: ") 
        mark2 = raw_input("Enter marks 2: ") 
        mark3 = raw_input("Enter marks 3: ") 
        str=indexNo + "," + mark1 +  "," + mark2 +  ","  + mark2 + "\n"
        file.write (str)
file.close()
if you are writing python 2.9 code input should be used instead of raw_input