There are three built-in functions for I/O handling in Python, let's go through them one by one.
Parameters:
Explanation: Reads input from standard input devices (such as keyboard) and takes it input as string.
## Take input from user
v = input() # or "input('Your message here ')"
print(type(v)) # <class 'str'>
print(v)
Parameters:
*
indicates more than one object.str
]: A separator between multiple values, default is a whitespace.str
]: The last print value, default is a newline.bool
: Whether to forcibly flush the stream.Explanation: Prints the given object to a standard output device, usually screen.
## Print output to the screen
print("This is output") # This is output
print("multiple", "objects", "to print") # multiple objects to print
## Pass variables to print
var1 = var2 = 42
print("The value of var is:", var1) # The value of var is: 42
print("var is", var1, "right?") # var is 42 right?
# format string with numbers are more readable
print("vars are {0} and {1}".format(var1, var2)) # vars are 42 and 42
# or simply using f shorthand as it is more convenient
print(f"vars are {var1} and {var2}") # vars are 42 and 42
## 'sep' and 'end' parameters
# Use the 'sep' parameter on prints
print("This", "is", "a", "String", sep="_") # This_is_a_String
# Use 'end' parameter to change print's end value
print("This", end="\t")
print("is not new line") # This is not new line
Parameters:
str
, bytes
]: String or byte path to a file.str
: Opening file mode.int
: For specifying buffering policy.str
]: Specify encoding format. On Windows the default is "cp1252" and "utf-8" on Linux/OSX.str
]: To handle Encoding/Decoding errors.str
]: Specify how the newline works.bool
: If set to False
, the underlying file descriptor will be kept open even when the file is closed.str
, int
], int
]]: A custom file opener, it should return a file descriptor.Explanation: This function is used to open a file. It returns a file object (also called handle), this object is further used to perform operations such as read/write/append to a file. For different types of operations there are different modes available, default is "r" (reading).
## Write to a file, 'PermissionError' is raised if Python doesn't have
# the permission
file = open("sample.txt", mode="w")
file.write("This is some text written to this file.")
file.close()
## Append mode
file = open("sample.txt", mode="a")
file.write("Previous content will not be overwritten.")
file.close()
## Read from a file, 'FileNotFoundError' is raised if the file is not found
file = open("sample.txt", mode="r")
# or open("sample.txt")
print(file.read()) # This is some text written to this file. \
# Previous content will not be overwritten.
file.close()
## Best practice is to write 'open()' in a 'try..except' block
try:
file = open("sample.txt", mode="r")
# do something
except FileNotFoundError:
print("The file does not exist")
finally:
file.close()
## Example 1: Text format and write mode
file = open("sample.txt", mode="tw")
file.write("This is some text written to the file")
file.close()
## Example 2: Read and append mode
file = open("sample.txt", mode="r+")
print(file.read()) # This is some text written to the file
file.write("Appending some more text in here.")
file.close()
## Example 3: Binary format and read mode, create a 'some.py' in
# current directory
file = open("some.py", mode="br")
print(file.read())
file.close()
## Reading
# read all text/non-text data at once, returns string/bytes
file = open("sample.txt", mode="r")
print(file.read())
# read all text/non-text data line by line, returns string/byte list
print(file.readlines())
## Writing
# write single string to the file
file.write("This is some text.")
# take a iterable object containing multiple strings and writes to the file
file.writelines(["This is a text.", "This is also some text"])
# close a file, frees up system resources, should be called as the last step
file.close()