Chapter 14: Files

Example 14.1, Page number: 454

In [2]:
#Write data to text file and read it

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','a')

#Write data to file if successfully created the file
if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    sys.stdout.write("Write data & to stop press '.'")
    c = ''
    while c != '.':
        c = raw_input("Write data & to stop press '.'")
        fp.write(c)
    fp.close()

    #Read and display the contents of file
    sys.stdout.write("\nContents read : ")
    fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')
    f = fp.readlines()
    for f1 in f:
        print f1
Write data & to stop press '.'Write data & to stop press '.'ABCDEFGHIJK
Write data & to stop press '.'.

Contents read : ABCDEFGHIJK.

Example 14.2, Page number: 455

In [16]:
#Display the contents of the file before and after appending.

import sys

#Open file for read data
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')

#Read and display the contents of file
sys.stdout.write("\nContents of file before appending :\n")
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')
f = fp.readlines()
for f1 in f:
    print f1

#Open file for appending
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','a')

if f == 0:
    sys.stdout.write("File can not appended")
else:
    c = ''
    #fp.write('\n')
    while c != '.':
        c = raw_input("Enter string to append")
        fp.write(c)
    
    fp.close()
    
   #Read and display the contents of file
    sys.stdout.write("\nContents of file After appending\n")
    fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')
    f = fp.readlines()
    for f1 in f:
        print f1
Contents of file before appending :
String is terminated with '\0'.

Contents of file After appending
String is terminated with '\0'.This character is called as NULL character.

Example 14.3, Page number: 457

In [5]:
#Writing and reading of a file.

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','w+')

#Write data to file if successfully created the file
if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    sys.stdout.write("Write data & to stop press '.'")
    c = ''
    while c != '.':
        c = raw_input("Write data & to stop press '.'")
        fp.write(c)
    fp.close()

    #Read and display the contents of file
    sys.stdout.write("\nContents read : ")
    fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')
    f = fp.readlines()
    for f1 in f:
        print f1
Write data & to stop press '.'
Contents read : ABCDEFGHIJK.

Example 14.4, Page number: 458

In [2]:
#Open a file in append mode and add new records in it.

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','a+')

#Write data to file if successfully created the file
if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    sys.stdout.write("Write data & to stop press '.'")
    c = ''
    while c != '.':
        c = raw_input("Write data & to stop press '.'")
        fp.write(c)
    fp.close()

    #Read and display the contents of file
    sys.stdout.write("\nContents read : ")
    fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','a+')
    f = fp.readlines()
    for f1 in f:
        print f1
Write data & to stop press '.'
Contents read : This is append and read mode.

Example 14.5, Page number: 459

In [2]:
#Open a file in read/write mode in it

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r+')

#Write data to file if successfully created the file
if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    #Read and display the contents of file
    sys.stdout.write("\nContents read : ")
    f = fp.readlines()
    for f1 in f:
        print f1
        
    sys.stdout.write("Write data & to stop press '.'")
    c = ''
    while c != '.':
        c = raw_input("Write data & to stop press '.'")
        fp.write(c)
    fp.close()
Contents read : Help me.
Write data & to stop press '.'

Example 14.6, Page number: 460

In [3]:
#Open a file for read/write operation in binary mode

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','wb')

#Write data to file if successfully created the file
if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    sys.stdout.write("Write data & to stop press '.'")
    c = ''
    while c != '.':
        c = raw_input("Write data & to stop press '.'")
        fp.write(c)
    fp.close()

    #Read and display the contents of file
    sys.stdout.write("\nContents read : ")
    fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','rb')
    f = fp.readlines()
    for f1 in f:
        print f1
Write data & to stop press '.'
Contents read : ABCDEFGHIJK.

Example 14.7, Page number: 462

In [4]:
#Open a text file and write some text 

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','w')

#Read the string
text = raw_input("Enter Text Here : ")

#Write to the file
#fp.write() is the equivalent function for fprintf() in python
fp.write("%s"%(text))

#To see the result, open the data.txt file

Example 14.8, Page number: 463

In [15]:
#Enter data into the text file and read the same.  

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','w')

#Read the data
text = raw_input("Name & Age")
age = int(raw_input("Name & Age"))

#Write to file
fp.write("%s   %d"%(text,age))

fp = open('C:\Users\Aathira\Documents\IPython Notebooks\data.txt','r')
#Result
sys.stdout.write("Name\tAge\n")
text = fp.read()
age = fp.read()
sys.stdout.write("%s\t%s\n"%(text,age))
fp.close()
Name	Age
AMIT   12	

Example 14.9, Page number: 463

In [1]:
#Read the contents of the file 

import sys

#Open file
f = open('C:\Users\Aathira\Documents\IPython Notebooks\list.txt','r')

if f == 0:
    sys.stdout.write("Cannot open file")
else:
    for c in f:
        sys.stdout.write("%s"%(c))
    #Python gives iterative statements there is no getc() fucntion
aman
akash
amit
ajay
ankit

Example 14.10, Page number: 464

In [3]:
#Write some text into the file 

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\words.doc','w')

#Write data to file
c = ''
while c != '*':
    c = raw_input("Enter Few Words '*' to Exit")
    fp.write(c)

fp.close()
    #There is no putc() function in python
    #Open the file to see the result

Example 14.11, Page number: 465

In [8]:
#Count

# Total number of statements
# Total number of included files
# Total number of blocks and brackets

import sys

#Open file
fs = open('C:\Users\Aathira\Documents\IPython Notebooks\PRG2.C','r')

#variable initialization
i = 0
c = 0
sb = 0
b = 0

if fs == 0:
    sys.stdout.write("File opening error")
else:
    for line in fs:
        k = 0
        while k < len(line):
            if line[k] == ';':
                c += 1
            else:
                if line[k] == '{':
                    sb += 1
                else:
                    if line[k] == '(':
                        b += 1
                    else:
                        if line[k] == '#':
                            i += 1
            k += 1
                            
    #Result
    sys.stdout.write("\nSummary of 'C' Program\n")
    sys.stdout.write("===========================")
    sys.stdout.write("\nTotal Statments : %d"%(c+i))
    sys.stdout.write("\nInclude Statements : %d"%(i))
    sys.stdout.write("\nTotal Blocks {} : %d"%(sb))
    sys.stdout.write("\nTotal Brackets () : %d"%(b))
    sys.stdout.write("\n============================")
                            
Summary of 'C' Program
===========================
Total Statments : 8
Include Statements : 2
Total Blocks {} : 2
Total Brackets () : 9
============================

Example 14.12, Page number: 466

In [10]:
#Write text to a file 

import sys

#Open file
fp = open('C:\Users\Aathira\Documents\IPython Notebooks\lines.txt','w')

if fp == 0:
    sys.stdout.write("")
else:
    #Write data to file
    c = ''
    while c != '*':
        c = raw_input("")
        fp.write(c)
    fp.close()
    #There is no fputc() function in python
    #Open the file to see the result

Example 14.13, Page number: 467

In [11]:
#Read text from the given file 

import sys

#Open file

file1 = raw_input("Enter File Name : ")
fp = open(file1,'r')

if fp == 0:
    sys.stdout.write("File not found\n")
else:
    for text in fp:
        print text
    #File pointer itself is iterable in python
#include <stdio.h>

Example 14.14, Page number: 468

In [13]:
#Write a string into a file 

import sys

#Open file

file1 = raw_input("Enter the name of file : ")
fp = open(file1,'w')

if fp == 0:
    sys.stdout.write("File can not opened\n")
else:
    text = raw_input("Enter Text Here : ")
    fp.write(text)
    
    #Write() function is used to write character or string into the file in python
    # there is no fputc() function in python
#open the file to see the result

Example 14.15, Page number: 469

In [3]:
#Write integers in a file 

import sys

#Open file
fp = open('num.txt','w')

if fp == 0:
    sys.stdout.write("File does not exist\n")
else:
    v = ' '
    while v != '0':
        fp.write(v)
        v = raw_input("Enter Numbers")
        
        #open the file to see the result

Example 14.16, Page number: 470

In [1]:
#Read integers from the file 

import sys

#Open file
fp = open('num.txt','r')

if fp == 0:
    sys.stdout.write("File does not exist\n")
else:
    for v in fp:
        print v
1 2 3 4 5

Example 14.17, Page number: 471

In [3]:
#Write a block of structure elements to the given file 

import sys

#Class declaration
class student:
    name = ''
    age = 0
    
#Class variable declaration
stud = [student() for i in range(0,5)]

#Open file
file1 = raw_input("Enter the file name : ")
fp = open(file1,'w')

if fp == 0:
    sys.stdout.write("File does not exist\n")
else:
    n = int(raw_input("How Many Records : "))
    for i in range(0,n):
        stud[i].name = raw_input("Name  : ")
        stud[i].age = int(raw_input("Age : "))
    
    j = 0
    while j < n:
        fp.write("%s %d\n"%(stud[j].name,stud[j].age))
        j += 1
        
    fp.close()
    
    #open the file to see the result

Example 14.18, Page number: 472

In [3]:
#Write and read the information about the player 

import sys

#Class declaration
class record:
    player = ''
    age = 0
    runs = 0
    
#Class variable declaration
emp = record()

#Open file
fp = open('record.dat','w')

if fp == 0:
    sys.stdout.write("Can not open the file\n")
else:
    emp.player = raw_input("Enter Player Name")
    emp.age = int(raw_input("Enter Age"))
    emp.runs = int(raw_input("Enter runs scored"))
    fp.write("%s %d %d"%(emp.player,emp.age,emp.runs))
    fp.close()
    
    fp = open('record.dat','r')
    if fp == 0:
        sys.stdout.write("Error in opening file")
    else:
        sys.stdout.write("\nRecord Entered is\n")
        emp.player,emp.age,emp.runs = fp.read().split(' ')
        sys.stdout.write("\n%s  %s  %s"%(emp.player,emp.age,emp.runs))
        fp.close()
Enter Player NameSachin
Enter Age25
Enter runs scored10000

Record Entered is

Sachin  25  10000

Example 14.19, Page number: 473

In [5]:
#Write a block of structure elements to the given file 

import sys

#Variable Initialization
next1 = 'Y'

#Class declaration
class bike:
    name = ''
    avg = 0
    cost = 0.0
    
#Class variable declaration
e = bike()

#open file
fp = open('bk.txt','wb')

if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    while next1 == 'Y':
        e.name = raw_input("Model Name")
        e.avg = int(raw_input("Average"))
        e.cost = float(raw_input("Price"))
        fp.write("%s %d %f\n"%(e.name,e.avg,e.cost))
        
        next1 = raw_input("Add Another (Y/N):")
    fp.close()
Model NameHONDA
Average80
Price45000
Add Another (Y/N):Y
Model NameSUZUKI
Average65
Price43000
Add Another (Y/N):Y
Model NameYAMAHA
Average55
Price48000
Add Another (Y/N):N

Example 14.20, Page number: 474

In [1]:
#Read the information about the bike 

import sys

#Class declaration
class bike:
    name = ''
    avg = 0
    cost = 0.0
    
#Class variable declaration
e = bike()

#open file
fp = open('bk.txt','rb')

if fp == 0:
    sys.stdout.write("Cannot open file")
else:
    lines = fp.readlines()
    for line in lines:
        e.name,e.avg,e.cost = line.split(' ')
        e.avg = int(e.avg)
        e.cost = float(e.cost)
        sys.stdout.write("\n%s %d %.2f"%(e.name,e.avg,e.cost))
HONDA 80 45000.00
SUZUKI 65 43000.00
YAMAHA 55 48000.00

Example 14.21, Page number: 476

In [7]:
#Read the text after skipping n characters from beginning of the file

import sys

#Open file
fp = open("text.txt","r")

sys.stdout.write("\nContents of file\n")
ch = fp.read()
sys.stdout.write("%s"%(ch))

#Read n
n = int(raw_input("How many characters including spaces would you like to skip?"))

#Result
sys.stdout.write("\nInformation after %d bytes\n"%(n))

ch = ch[n:]
sys.stdout.write("%s"%(ch))

fp.close()
Contents of file
THE C PROGRAMMING LANGUAGE INVENTED BY DENNIS RITCHIEHow many characters including spaces would you like to skip?18

Information after 18 bytes
LANGUAGE INVENTED BY DENNIS RITCHIE

Example 14.22, Page number: 477

In [9]:
#Read last few characters of the file 

import sys

#Open file
fp = open("text.txt","r")

sys.stdout.write("\nContents of file\n")
ch = fp.read()
sys.stdout.write("%s"%(ch))

#Read n
n = int(raw_input("How many characters including spaces would you like to skip?"))

#Result
sys.stdout.write("\nInformation after %d bytes\n"%(n))

print ch[-n:]

fp.close()
Contents of file
HELLO WORLDHow many characters including spaces would you like to skip?5

Information after 5 bytes
WORLD

Example 14.23, Page number: 477

In [20]:
#Display 'c' program files in current directory. 

import sys

#Variable initialization
l = 0
c = 0

#Open file
file1 = raw_input("Enter the file name : ")
fp = open(file1,'r')

#Result
sys.stdout.write("\nContents of 'c' program file in capital case")
sys.stdout.write("\n============================================\n")

ch = fp.readlines()

for line in ch:
    i = 0
    #print line.upper()
    while i < len(line):
        if line[i] =='\n':
            l += 1
        else:
             c += 1
        sys.stdout.write("%c"%(line[i].upper()))
        i += 1

sys.stdout.write("\nTotal Characters : %d"%(c))
sys.stdout.write("\nTotal Lines : %d"%(l))
Contents of 'c' program file in capital case
============================================
MAIN()
{
PRINTF(" HELLO WORLD");
}

Total Characters : 31
Total Lines : 4

Example 14.24, Page number: 479

In [26]:
#Detect the end of file 

import sys

#Open file
fp = open("text.txt","r")

#there is no feof() function in python
c = fp.tell()
sys.stdout.write("File pointer at the beginning of the file : %d\n"%(c))

c = fp.read()
sys.stdout.write("%s"%(c))

c = fp.tell()
sys.stdout.write("\nFile pointer at the end of file : %d"%(c))
File pointer at the beginning of the file : 0
TECHNOCRATS LEAD THE WORLD      
File pointer at the end of file : 32

Example 14.25, Page number: 480

In [10]:
#Detect an error while read/write operation of a file is in use.

import sys

#Variable initialization
next1 = 'Y'

#open file
fp = open('marks.dat','r')

if fp == 0:
    sys.stdout.write("Can not open file")
else:
    while next1 == 'Y':
        name = raw_input("Enter Name, Marks, Percentage")
        marks = int(raw_input("Enter Name, Marks, Percentage"))
        
        p = marks/7
        try:
            fp.write("%s %d %f"%(name,marks,p))
        except:
            sys.stdout.write("\nUnable to write data?")
            sys.stdout.write("\nFile opening mode is incorrect.")
            fp.close()
            
        next1 = raw_input("Continue Y/N:")
Enter Name, Marks, PercentageKAMAL
Enter Name, Marks, Percentage540

Unable to write data?
File opening mode is incorrect.Continue Y/N:N

Example 14.26, Page number: 481

In [1]:
#Catch the error that is occurred while file operation

import sys

#Open file
f = open("io8.c","w")

if f == 0:
    sys.stdout.write("\nCannot open file")
else:
    #Exception handling
    try:
        c = fp.readlines()
        sys.stdout.write("%s"%(c))
    except:
        sys.stdout.write("\nCan't read file.")
#There is no ferror() function python.
Can't read file.

Example 14.27, Page number: 482

In [1]:
#Detect and print the error message

import sys

#Variable Initialization
file1 = "lines.txt"

#Open file
fr = open(file1,"w")

sys.stdout.write("%s  : "%(file1))
#Exception handling
try:
    c = fp.readlines()
except:
    sys.stdout.write("Permission Denied")
    
lines.txt  : Permission Denied

Example 14.28, Page number: 482

In [12]:
#Print the current position of the file pointer 

import sys

#Open file
fp = open("text.txt","r")

#Set the pointer
fp.seek(21)

#Result
while True:
    c = fp.read(1)
    if not c:
      break
    sys.stdout.write("%c\t%d\n"%(c,fp.tell()))
#There is no endof file in python
W	22
O	23
R	24
L	25
D	26

Example 14.29, Page number: 483

In [25]:
#Detect beginning of file

import sys

#open file
fp = open("text.txt","r")

fp.seek(12)
sys.stdout.write("Pointer is at %d\n"%(fp.tell()))
sys.stdout.write("Before rewind() : ")

#Result
while True:
    c = fp.read(1)
    if not c:
      break
    sys.stdout.write("%c"%(c))
    
sys.stdout.write("\nAfter rewind() : ")
fp.seek(0)
#There is no rewind function in python

while True:
    c = fp.read(1)
    if not c:
      break
    sys.stdout.write("%c"%(c))
    
fp.close()
Pointer is at 12
Before rewind() : LEAD THE WORLD
After rewind() : TECHNOCRATS LEAD THE WORLD

Example 14.30, Page number: 484

In [13]:
#Delete the given file 

import sys
import os

#Read file name
file1 = raw_input("Enter The File Name : ")

#There is no remove or unlink file function in python.
#A file can be deleted using remove function in the os module.

try:
    os.remove(file1)
    sys.stdout.write("\nFile (%s) has been deleted!"%(file1))
except:
    sys.stdout.write("\nFile does not exist")

    
File (TEXT.TXT) has been deleted!

Example 14.31, Page number: 485

In [22]:
#Change the name of the file

import os
import sys

old = raw_input("Old File Name : ")

new = raw_input("New File Name : ")

os.rename(old, new)

#Check the directory to see the result

Example 14.32, Page number: 486

In [5]:
#Copy the contents of one file to another file

import sys

fs = open("a.txt","r")
ft = open("b.txt","w")
c = 0

if fs == 0:
    sys.stdout.write("\nSource file opening error.")
else:
    if ft == 0:
        sys.stdout.write("\nTarget file opening error.")
    else:
        while True:
            ch = fs.read(1)
            if not ch:
                break
            ft.write("%c"%(ch))
            c += 1
        sys.stdout.write("\n%d Bytes copied from 'a.txt' to 'b.txt'."%(c))
        c = 0
        #there is no fcloseall() function in python
        fs.close()
        c += 1
        ft.close()
        c += 1
        sys.stdout.write("\n%d files closed."%(c))
45 Bytes copied from 'a.txt' to 'b.txt'.
2 files closed.

Example 14.33, Page number: 487

In [16]:
#Read the contents of three files and find the largest file

import sys

#Variable Initialization
y = 0
k = 0
t = 0
name = ["1.txt","2.txt","3.txt"]
f = [0 for i in range(0,3)]
x = [0 for i in range(0,3)]

#Open all the files
for l in range(0,3):
    fp = open(name[l],"r")
    f[l] = fp
    if fp == 0:
        sys.stdout.write("\n%s file not found."%(name[l]))
        break
        
#Read contents of all files
for l in range(0,3):
    while True:
        c1 = f[l].read(1)
        if not c1:
            break
        x[l] = y
        y += 1
    y = 0

#close the files
for l in range(0,3):
    f[l].close()

#Print size of all files
for l in range(0,2+1):
    sys.stdout.write("File : %s Bytes : %d\n"%(name[l],x[l]))
    t = t + x[l]
    
#Find largest
for l in range(t,1,-1):
    for k in range(0,3):
        if l == x[k]:
            sys.stdout.write("\n%s are the largest file."%(name[k]))
            break
    if l == x[k]:
        break
File : 1.txt Bytes : 16
File : 2.txt Bytes : 20
File : 3.txt Bytes : 25

3.txt are the largest file.

Example 14.34, Page number: 488

In [1]:
#Copy 100 characters from a file to an array

import sys

#Variable Initialization
SIZE = 100
s = 0
x = 0
ch = ['0' for i in range(0,100)]

#Open the files
f = open("poem.txt","r")
f2 = open("alpha.txt","w")

if f ==0 or f2 == 0:
    sys.stdout.write("?")
else:
    while True:
        c = f.read(1)
        x += 1
        if not c:
            break
        else:
            if x == 99:
                break
            else:
                ch[s] = c
                s += 1

for s in range(0,100):
    f2.write("%c"%(ch[s]))

sys.stdout.write("Process Completed : Error 0")
f.close()
f2.close()

#There is no perror() function in python
Process Completed : Error 0

Example 14.35, Page number: 491

In [11]:
#Low level disk I/O operations.

import sys


#Variable Initialization
file1 = raw_input("Enter a file name : ")

#Open file
s = open(file1,"w")

#Result
if s == -1:
    sys.stdout.write("File does not exits")
else:
    buff = raw_input("Enter text below:")
    s.write("%s"%(buff))
    s.close()
Enter a file name : TEXT
Enter text below:PROGRAMMING IN C

Example 14.36, Page number: 492

In [12]:
#Read text from a specified file 

import sys

#Variable initialization
file1 = raw_input("Enter a file name ")

#open file
s = open(file1,"r")

#Result
if s == -1:
    sys.stdout.write("File does not exists")
else:
    while True:
        ch = s.read(1)
        if not ch:
            break
        sys.stdout.write("%c"%(ch))
        
s.close()
Enter a file name TEXT
PROGRAMMING IN C

Example 14.37, Page number: 493

In [6]:
#Set a buffer size 

import sys

#Result
sys.stdout.write("\nThis book teaches C")
This book teaches C

Example 14.38, Page number: 494

In [8]:
#Display number of arguments and their names

import sys

#Result
sys.stdout.write("\nTotal number of arguments are %d\n"%(len(sys.argv)))

print str(sys.argv)

#Command line arguments can be given in python by the command

#   python pgmname.py arg1 arg2 arg3

#This is not possible in ipython notebook

Example 14.39, Page number: 495

In [ ]:
#Read any file from command prompt

import sys

#open file
fp = open(sys.argv[1],"r")

#Result
if fp == 0:
    sys.stdout.write("Can not open file")
else:
    while True:
        ch = fp.read(1)
        if not ch:
            break
        sys.stdout.write("%c"%(ch))
        
fp.close()

#This program can be run in python as

#   python pgmname.py filename

Example 14.40, Page number: 495

In [ ]:
#Command line argument to perform the task of DEL command

import sys

#Check number of arguments
if len(sys.argv) < 2:
    sys.stdout.write("Insufficient Arguments")
else:
    fp = open(sys.argv[1],"r")
    if fp == 0:
        sys.stdout.write("File Not Found")
        fp.close()
        os.remove(sys.argv[1])
        sys.stdout.write("File has been deleted")
        
#This program can be deleted using
#     python pgmname.py filename

Example 14.41, Page number: 496

In [ ]:
#Command line argument to perform the task of REN command

import sys

#Check number of arguments
if len(sys.srgv) < 3:
    sys.stdout.write("Insufficient Arguments")
else:
    fp = open(sys.argv[1],"r")
    if fp == 0:
        sys.stdout.write("File Not Found")
    else:
        sp = open(sys.argv[2],"r")
        if sp == 0:
            fp.close()
            sp.close()
            #Rename file
            os.rename(sys.argv[1],sys.argv[2])
        else:
            sys.stdout.write("Duplicate file name or file is in use")
            
#This program can be executed as

#   python pgmname.py oldfilename newfilename

Example 14.42, Page number: 497

In [3]:
#Environment variable and display the various settings.

import sys
import os

#Result
print os.environ
{'TMP': 'C:\\Users\\Aathira\\AppData\\Local\\Temp', 'COMPUTERNAME': 'AATHIRA-PC', 'GUROBI_HOME': 'B:\\gurobi510\\win32', 'USERDOMAIN': 'Aathira-PC', 'PSMODULEPATH': 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\', 'COMMONPROGRAMFILES': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 15 Stepping 13, GenuineIntel', 'PROGRAMFILES': 'C:\\Program Files (x86)', 'PROCESSOR_REVISION': '0f0d', 'SYSTEMROOT': 'C:\\Windows', 'PATH': 'C:\\Anaconda\\lib\\site-packages\\numpy\\core;B:\\gurobi510\\win32\\bin;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\Common Files\\Adobe\\AGL;C:\\Program Files\\MATLAB\\R2009a\\bin;C:\\Program Files\\MATLAB\\R2009a\\bin\\win64;c:\\python27\\scripts;C:\\Program Files (x86)\\MiKTeX 2.9\\miktex\\bin\\;C:\\Anaconda;C:\\Anaconda\\Scripts;C:\\Program Files (x86)\\ffmpeg', 'CLICOLOR': '1', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'TK_LIBRARY': 'C:\\Anaconda\\tcl\\tk8.5', 'TERM': 'xterm-color', 'TEMP': 'C:\\Users\\Aathira\\AppData\\Local\\Temp', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'PROCESSOR_ARCHITECTURE': 'x86', 'TIX_LIBRARY': 'C:\\Anaconda\\tcl\\tix8.4.3', 'ALLUSERSPROFILE': 'C:\\ProgramData', 'LOCALAPPDATA': 'C:\\Users\\Aathira\\AppData\\Local', 'HOMEPATH': '\\Users\\Aathira', 'PROGRAMW6432': 'C:\\Program Files', 'USERNAME': 'Aathira', 'LOGONSERVER': '\\\\AATHIRA-PC', 'SESSIONNAME': 'Console', 'PROGRAMDATA': 'C:\\ProgramData', 'TCL_LIBRARY': 'C:\\Anaconda\\tcl\\tcl8.5', 'GIT_PAGER': 'cat', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC', 'FP_NO_HOST_CHECK': 'NO', 'WINDIR': 'C:\\Windows', 'APPDATA': 'C:\\Users\\Aathira\\AppData\\Roaming', 'HOMEDRIVE': 'C:', 'PAGER': 'cat', 'SYSTEMDRIVE': 'C:', 'NUMBER_OF_PROCESSORS': '2', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_ARCHITEW6432': 'AMD64', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'OS': 'Windows_NT', 'PUBLIC': 'C:\\Users\\Public', 'USERPROFILE': 'C:\\Users\\Aathira'}

Example 14.43, Page number: 498

In [9]:
#Read character from keyboard 

import sys

c = '0'

#Result
while c != ' ':
    c = raw_input("")
    sys.stdout.write("%c  "%(c))
    
#Give space at the end
1  2  3  4  5  6  7  8  9     

Example 14.44, Page number: 499

In [11]:
#Display A to Z characters

import sys

#Result
for a in range(65,91):
    sys.stdout.write("%c\t"%(chr(a)))
A	B	C	D	E	F	G	H	I	J	K	L	M	N	O	P	Q	R	S	T	U	V	W	X	Y	Z	
In [ ]: