Python: I/O Operations
In this article we show how we can to input/output operations using user input and file. Python supports standard keyboard input and screen output using input and print keywords, respectively. File I/O has more option depending if you want to write, read or append a file. Python also supports text and binary mode of writing,however both modes have a very minor difference based on how cr-lf ('\r\n') is handled.
The following code sample demonstrate how interactive user input and output are handled in Python. After that we look at code sample to perform File I/O. Inline comments (starting with #) clarify the purpose of specific lines of code.
# Code for demonstration of Python Dictionary
class DemoScreenIOClass:
def ReadFromKeyboard(self):
print("---------- ReadFromKeyboard")
# Read a value from keyboard
self.__value = input('Enter any value:')
# Validation can be added using a try-except block
self.__numValue = -1
try:
self.__numValue = int(input('Enter a numeric value:'))
except ValueError:
print("Not a number")
def OutputToScreen(self):
print("---------- OutputToScreen")
print('Print is used to output to screen')
#Output to screen is done using the print statement
print('Entered value is ', self.__value)
# Multiple variables can be printed by separating them in commas ','
print('Entered values are ', self.__value, self.__numValue)
dsc=DemoScreenIOClass()
dsc.ReadFromKeyboard()
dsc.OutputToScreen()
The output for the above code is:
---------- ReadFromKeyboard Enter any value:12 Enter a numeric value:cbelwal Not a number ---------- OutputToScreen Print is used to output to screen Entered value is 12 Entered values are 12 -1 Process finished with exit code 0
The following code sample handles File I/O:
class DemoFileIOClass:
def CreateFile(self):
print("----------- CreateFile")
# Open a file for writing
# If file exists it will be overwritten
# The 'w' implies a non-binary pure write mode
# Using 'wb' implies a binary write
# There is only a minor difference between text and binary read/write in Python
# The difference is in how binary and text writes treat CR-LF ('\r\n')
file = open("MyFile.txt", "w")
# Let us write from data
file.write("This is Sentence 1.")
file.write("This is Sentence 2.")
# Line breaks have to be explicitly specified
# In Windows, Python write will replace '\n' by '\r\n' if file is in text mode
# During file read '\r\n' will be replaced by '\n'
# If file opened in Binary mode, this replacement is not done
file.write("\nThis is Sentence 3 in the next line.")
# All write will be committed when file is closed or object id destroyed
# However it is always good to close the file explicitly.
file.close()
def ReadFromExistingFile(self):
print("----------- ReadFromExistingFile")
# Open a file for reading
# The 'r' implies a non-binary pure read mode
file = open('MyFile.txt', 'r')
# Read all bytes from file
value = file.read()
print("Read value is:", value)
# Reset the file pointer to the beginning of the file
file.seek(0)
# Read first 8 bytes from file
value = file.read(4)
print("Read 4 bytes, value is:", value)
# Read one line from file
value = file.readline()
print("Read 1 line, value is:", value)
# Reset the file pointer to the beginning of the file
file.seek(0)
# It is always good to close the file explicitly.
# Read all lines from file
# values will be a list
values = file.readlines()
print("Read all lines, value is: ", values)
file.close()
def ReadWriteToFile(self):
print("----------- ReadWriteToFile")
# Open a file for writing
file = open('MyFile.txt', 'w')
# Write some lines to file
file.write("V1, V2, V3, V4\n")
file.write("1, 2, 3, 4\n")
file.write("5, 6, 7, 8\n")
file.write("9, 10, 11, 12\n")
# Close the file so that buffer is flushed
file.close()
# The 'w+' implies a non-binary read/write mode
# 'r+' can also be used for non-binary read/write mode
file = open('MyFile.txt', 'r+')
# Now read the data for each line
# allLines will be a list containing content for each line
# CAUTION: Each line if identified by a CR ('\n'). If there is a LF ('\r') it will be
# counted as a separate line
allLines = file.readlines()
print("Number of lines read:", len(allLines))
print("Line at index 0:", allLines[0])
print("Line at index 3:", allLines[3])
# Now also write some more data to file
# This is equivalent to an append, this line will be added
file.write("13, 14, 15, 16\n")
# Close the file explicitly.
file.close()
# Append to a file
def AppendToFile(self):
print("----------- AppendToFile")
# The 'a+' implies a non-binary read/append mode
# If we use 'a' we cannot read from file
file = open('MyFile.txt', 'a+')
file.write("17, 18, 19, 20\n")
# Set file pointer to start of file
# This is required if we want to read from the file without closing
# and reopening it
file.seek(0)
# Now read from file
value = file.read()
print("Content of file\n", value)
file.close()
def CheckFileMode(self):
file = open('MyFile.txt', 'a+')
# We can use file mode t find out the mode file was opened in
if file.mode == 'a+':
print("File mode is a+")
file.close()
dfc = DemoFileIOClass()
dfc.CreateFile()
dfc.ReadFromExistingFile()
dfc.ReadWriteToFile()
dfc.AppendToFile()
dfc.CheckFileMode()
The output for the above code is:
----------- CreateFile ----------- ReadFromExistingFile Read value is: This is Sentence 1.This is Sentence 2. This is Sentence 3 in the next line. Read 4 bytes, value is: This Read 1 line, value is: is Sentence 1.This is Sentence 2. Read all lines, value is: ['This is Sentence 1.This is Sentence 2.\n', 'This is Sentence 3 in the next line.'] ----------- ReadWriteToFile Number of lines read: 4 Line at index 0: V1, V2, V3, V4 Line at index 3: 9, 10, 11, 12 ----------- AppendToFile Content of file V1, V2, V3, V4 1, 2, 3, 4 5, 6, 7, 8 9, 10, 11, 12 13, 14, 15, 16 17, 18, 19, 20 File mode is a+ Process finished with exit code 0
Thanks for such a great article here.
ReplyDeletePython Online Training