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.


'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")

How to read a text file

file = open('newfile.txt', 'r')
print file.read()
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) 

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():
hello python

file.readlines( )

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

Looping over a file object

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

for line in file:
    print line,

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")

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")
while (running ==1) :
    indexNo = raw_input("Enter Index No: ") 
    if (indexNo=="-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)
if you are writing python 2.9 code input should be used instead of raw_input

Thursday, February 11, 2016

SL Design Hack 1.0 : Animation & Graphics Competition

SL Design Hack 1.0 organised by Young Artists Society Sri Lanka, founded by Shilpa Sayura Youth. It aims to unleash best creativity in Youth to identify best designers and help them reach higher level in creative field.


Competition Information

Theme: Youth and Internet - issues and Solutions

Competition Areas
20 second Animation
Graphic Design

Junior (16 and below)
Senior  (19 and below)
Open  (20+)

1. Become a member of Young Artist Society Sri Lanka
2. Join SL Hack 1.0 Event
3. Submit Your Competition Registration { opening on Feb 20}

Share the competition on your page

How to take part in Competition
You can join online or from a local hack spot to the event.
  • A Hack spot can be a home , school, office or public place with food, water and electricity.
  • You can invite who ever you like to local hack and upload creatives to the competition page.
  • If you like to run a HACK SPOT contact us for support and information

How to take part
You can apply for Animation or Graphics Competition or Both.
You can submit any number of creatives for each category or sector, but you may win only one prize.
Your animation or graphic should reflect your expression
on Internet and Youth - Issues and Solutions theme.

Technique and Tools
You may use any tools to create animation or graphics and need to upload them as 20s videos or photos 800 x 600 high quality JPG.

Sinhala , Tamil or English, Sign  or No language accepted.

The content of the animation or graphic should be suitable for all audience regardless of age.
No content accepted that promote harassment, violence  and hate speech against any culture, community or religion.

Dates and Times
March 7  Monday 9 AM -  March 8 9 AM Sri Lanka Time (IST)
You should submit your creatives during this period only.

Your creative work submitted for the  SL Design HACK 1.0 will be promoted on internet for 10 days for public feedback. 10 finalists chosen from each section and age category.
(2 x 3 x 10 =60 creatives.) . The finalist creatives will be called for public voting.

Judges from creative, technical sector  will evaluate the finalist creatives and select a Winner and Runner up for each section and age category . Public choice award given to most number of likes and shares by public. In case a competitor winning two places, the second place given to next under one price per one person.

Judging CriteriaOriginality, Visual Presentation, Techniques and Message. Judges decision shall be final.

Awards & Certificates
  • Open : Animation Winner, Runner Up and Public Choice -  3 Awards
  • Open : Graphics Design Winner, Runner Up and Public Choice - 3 Awards
  • Senior  : Animation Winner, Runner Up and Public Choice Awards - 3 Awards
  • Senior : Graphics Design Winner, Runner Up and Public Choice - 3 Awards
  • Junior  : Animation Winner, Runner Up and Public Choice Awards - 3 Awards
  • Junior : Graphics Design Winner, Runner Up and Public Choice - 3 Awards
  • Certificate for 60 finalists 
What Next ?
The Top 3 Senior and Junior Creations for Animation and Graphics category submitted to Adobe Aspire Awards. The Open section creatives submitted to Adobe design awards. That would enable their admittance to Adobe Youth Voices program to win a creative scholarships.

Planned dates 
  • March 7-8 - Design Hack
  • March - 9 - 16 - Finalist Selection
  • March 17 - 26 - Public Voting
  • March 27 - Final Judging & Result
  • Awards Date : To be fixed ...

All creative works are copy right of the creator. They may submitted to competition with creative commons license with no commercial use and no derivatives terms.

Supported by

Saturday, January 9, 2016

Hacker Rank Python Number List Solution with 3.x and 2.x

Problem Statement
An array A consist of N positive integers. List all the subarrays of array and replaced all the subarrayswith the maximum element present in the respective sub array.
View Problem at Hacker Rank
def numberList(a ,k): result = 0 big = -1 alen=0 #print(a) for val in a: a[alen]=int(a[alen]) alen=alen+1 #print (alen) k=int(k); for i in range(alen): if a[i] > k: result += (i-big)*(alen-i) big = i return result if __name__ == '__main__': t = int(input()) for _ in range(t): n,k = input().split() a = input().split() print(numberList(a ,k))
Python 2.x Solution

def numberList(a ,k):
    result = 0
    big = -1
    alen = len(a)
    for i in xrange(alen):
        if a[i] > k:
            result += (i-big)*(alen-i)
            _big = i
    return result
if __name__ == '__main__':
    t = int(raw_input())
    for _ in xrange(t):
        n,k = map(int, raw_input().split())
        a = map(int, raw_input().split())
        print numberList(a ,k)

Differences of Syntax

1. print on Python 3.x uses ()
2. xrange() of Python changed to range()
3. python 3.x renamed raw_input() to input() in 3.x