File Write and Read
In this module, a simple simple three (3) field data base stored as a comma delimited text file will be created by one program and then read by the second program.
Writing to a file
#Text File write written in Python
print 'Write to a text file' #program heading
#main program
#create and open file for writing
f=open('friend.txt', 'w')
#get data
given = raw_input("Enter given name -> ")
surname = raw_input("Enter surname -> ")
age = raw_input("Enter age -> ")
onelineoftext = given + ',' + surname + ','+ age + '\n'
#write data to file
f.write(onelineoftext)
#add more data??
more = raw_input("Enter Y to add more or N to finish -> ")
while more == 'Y':
given = raw_input("Enter given name -> ")
surname = raw_input("Enter surname -> ")
age = raw_input("Enter age -> ")
onelineoftext = given + ',' + surname + ','+ age + '\n'
f.write(onelineoftext)
more = raw_input("Enter Y to add more -> ")
#close the file
f.close()
Note:
/n adds a newline sequence to the end of the line
Reading from a file
#Text File read written in Python
print 'Read from a text file' #program heading
#main program
#open the file for reading
f=open('friend.txt', 'r')
#read a line of text from file
onelineoftext = f.readline()
while onelineoftext != '':
print onelineoftext
onelineoftext = f.readline()
#close the file
f.close()
Note:
-
The "w" parameter in the open function allows you to create and write to a file.
-
The "a" parameter in the open function allows you to append to a file.
-
The "r" parameter in the open function allows you to read from a file.
Exercises
- Create a simple database management system by combining the two programs above into procedures. Then use an array to store your data while in memory. Create a simple sort function that will sort your data into age order.
- ex2
- ex3
[Python_Tutorial] [Sequence_Python] [Interation_Python] [Decision_Making_Python] [Arrays_Python] [Files_Python]
Comments (0)
You don't have permission to comment on this page.