Input-Output

There are many ways to print the output of the program. We can use print statements on the console, or we can print the output to the results of the file.

Printing on screen

One of the simple ways to output in the console is by using print() function.There are more keyword arguments that we can use on the print() function. We have: sep, end, file and flush keyword arguments. The sep, allows us to separate the objects, the end is to specify print at last, the file is used if we want to write the print statement into a file, and the flush is used to force the stream to be flushed (default value is false). Let’s see an example where we use all the keyword arguments:

 

string_var = " Using print function totally"
print("About:", string_var, sep="@@@@", end="!!!!", file=None, flush=False)

 

Output:About:@@@@ Using print function totally!!!!


Reading data from the keyboard

Input() which allows the program to read the input from the keyboard. Let’s have a look at the next example:

 

user_input = input("Write something: ")
print("You wrote: " + str(user_input))

 

Output:

Write something: hai
You wrote: hai


We are able to store the input from the user in a variable and call it later in our program.

Opening and closing file

Except the standard input and output, sometimes we need to store the information in data files. Python provides some functions that allow us to manipulate the files. For opening and closing a file, the python has the open() and close() functions.

The syntax to open a file is the following:

file_var = open(file_name, access_mode, buffering)

 

From the open syntax, only the file name must be pass in order to work. The access mode and buffering is optional,

 

file_var = open("file.txt")
file_var.close()


Reading, writing and appending into files

Following the process of opening and closing a file, we can read and write into files. From the open() syntax we have as the second parameter the “access mode” which provides as the option to read, to write and to append contents to a file.

 

read_file = open("read.txt","r")
print(read_file.read())
read_file.close()

 

Output: You have read the file

 

write_file = open("write.txt","w")
write_file.write("Write into this file")
print("Check the write.txt")
write_file.close()

 

Output:

Check the write.txt
write.txt fileWrite into this file

 

append_file = open("appending.txt","a")
append_file.write("Append into this file\n")
print("Check the appending.txt")
append_file.close()

 

Output:

Check the appending.txt
appending.txt file:
Append into this file

 

"r” in access mode in order to read the file.
“w” in access mode to be able to write into the file.
“a” in access mode to append any content to the file. 

 

Related Tutorials