fr = open("input.txt", "r")
fw = open("output.txt", "w")
my_str = fr.readline()
for letter in my_str:
fw.write(letter)
#close a file
fr.close()
fw.close()
fw = open("cities.txt", "w")
cities = ['Delhi\n','Madras\n','London\n'];
count = len(cities)
for city in cities:
fw.write(city)
fw.close()
fr = open("cities.txt", "r")
for line in fr.readlines():
print line,
"""
there is no bytes stream in Python. We will use normal file operations to copy from one file to another
"""
fr = open("in.txt", "r")
fw = open("out.txt", "w")
for line in fr.readlines():
fw.write(line)
fr.close()
fw.close()
fw = open("out.txt", "r")
for line in fw.readlines():
print line
"""
Note: In Python you can store data in file only as string.
"""
fos = open("prim.dat", "w")
fos.write(str(1999)+'\n')
fos.write(str(375.85)+'\n')
fos.write(str(False)+'\n')
fos.write("x"+'\n')
fos.close()
fis = open("prim.dat", "r")
for line in fis.readlines():
print line
fis.close()
from random import *
dos = open("rand.dat", "w")
try:
for i in range(20):
dos.write(str(randint(0,100))+'\n')
except IOError:
print IOError.message
finally:
dos.close()
dis = open("rand.dat", "r")
# Note: random numbers are generated so output will differ from that given in the textbook.
for line in dis.readlines():
print line,
file1 = open("file1.txt", "r")
file2 = open("file2.txt", "r")
file3 = open("file3.txt", "a")
for line in file1.readlines():
file3.write(line)
for line in file2.readlines():
file3.write(line)
file1.close()
file2.close()
file3.close()
fp = open("random.dat", "w+")
fp.write("x\n")
fp.write(str(555)+'\n')
fp.write(str(3.1412)+'\n')
fp.seek(0)
print fp.readline()
print fp.readline()
print fp.readline()
fp.seek(2)
print fp.readline()
fp.seek(fp.tell()+len(fp.readline()))
fp.write("False\n")
fp.seek(13)
print fp.readline()
fp.close()
fp = open("cities.txt", "a")
fp.write("Mumbai\n")
fp.close()
dos = open("invent.dat", "w")
dos.write(raw_input("Enter code number: ")+'\n')
dos.write(raw_input("Enter number of items: ")+'\n')
dos.write(raw_input("Enter cost: ")+'\n')
dos.close()
dis = open("invent.dat", "r")
codeNumber = int(dis.readline())
totalItems = int(dis.readline())
itemCost = int(dis.readline())
totalCost = totalItems*itemCost
dis.close()
print "Code Number: ", codeNumber
print "Item Cost: ", itemCost
print "Total Items: ", totalItems
print "Total Cost: ", totalCost