Chapter 14: File input/output

Example 14.1, Page number: 253

In [2]:
# Variable declaration
import os
count = 0
in_file = open ('input.txt', 'r')
 
# Calculation and result
if not os.path.exists ('input.txt') :
   print ('Cannot open input.txt\n')

while (1) :
   ch = in_file.read(1)
   if not ch :
      break
   count += 1

print ('Number of characters in input.txt is %d\n' % count)

in_file.close()
Number of characters in input.txt is 0

Example 14.3, Page number: 257

In [5]:
# Variable declaration
import sys
import os
in_file = open ('input.txt', 'r')
 
# Calculation and result
if not os.path.exists ('input.txt') :
   print ('Could not open file\n')
   sys.exit(1)
print ('File found\n')

in_file.close()
File found

Example 14.4, Page number: 260

In [3]:
# Variable declaration
import sys
import os
out_file = open ('test.out', 'w')
 
# Calculation and result
if not os.path.exists ('test.out') :
   print ('Cannot open output file\n')
   sys.exit(1)

for cur_char in range (0, 128) :
   out_file.write(str (cur_char))
   out_file.write('\n')

out_file.close()

Example 14.5, Page number: 267

In [ ]:
# Variable declaration
txt_file = open ('input.txt')

source_content = txt_file.read()

target = open ('output.txt', 'w')

# Calculation and result
target.write(source_content)
print ('Content copied')

target.close()