# Files : Opening and Closing
# Open the file for writing
file_pointer = open("first_file","w")
print "Enter text:"
# Get characters and place them in the file
text = "BASIC is easy,\nFORTAN is fun,\nPascal may be structured,\nBut C's the one!"
print text
file_pointer.write(text)
file_pointer.close()
file_pointer = open("first_file","r")
#Display the text from file
print "\nYou entered:"
print file_pointer.read()
file_pointer.close()
# Using several files
# Open the source file for reading
first_file_pointer = open("first_file","r")
# Open the destination file for writing
second_file_pointer = open("second_file","w")
# Transfer characters from source to destination file
c = first_file_pointer.read()
second_file_pointer.write(c)
# Close both files
first_file_pointer.close()
second_file_pointer.close()
# Open second file for displaying contentes
second_file_pointer = open("second_file","r")
print("'second_file' contains:")
print second_file_pointer.read()
# Append mode
# Open the first file for writing
first_file_pointer = open("first_file","w")
# Open the second file for appending
second_file_pointer = open("second_file","a")
# Writing to both files
first_file_pointer.write("\n--Anonymous\n")
second_file_pointer.write("\n--Anonymous\n")
# Close both files
first_file_pointer.close()
second_file_pointer.close()
# Display the contents of first file
first_file_pointer = open("first_file","r")
print("After write, 'first_file contains:")
print first_file_pointer.read()
# Display the contents of second file
second_file_pointer = open("second_file","r")
print("After append, 'second_file' contains:")
print second_file_pointer.read()
# The seek function
# Open file for reading
try :
file_pointer = open("second_file","r")
except :
print "'second_file' cannot be opened"
exit ()
# Skip the first 6 characters
file_pointer.seek(6,0)
print file_pointer.read()
# The 'w+' mode and seek to rewind a file
# Open a file for read/write
file_pointer = open("first_file","w+")
print "Enter text:"
text = "BASIC is easy,\nFORTAN is fun,\nPascal may be structured,\nBut C's the one!"
print text
file_pointer.write(text)
file_pointer.seek(0,0)
# Display the file
print "\nYou entered:"
print file_pointer.read()