Basic Input and Output

Basic Input and Output functions can be easily performed by using Python. Here is all you need to know about how to perform basic tasks.

Basic Input and Output: Using the print function

Python 3.x Version ≥ 3.0

In Python 3, print functionality is in the form of a function:

print("This string will be displayed in the output")

This string will be displayed in the output

print("You can print \n escape characters too.")
You can print escape characters too.
Python 2.x Version ≥ 2.3

In Python 2, print was originally a statement, as shown below.

print "This string will be displayed in the output"

This string will be displayed in the output

print "You can print \n escape characters too."

You can print escape characters too.

Note: using from future import print_function in Python 2 will allow users to use the print() function the same as Python 3 code. This is only available in Python 2.6 and above.

Basic Input and Output: Input from a File

Input can also be read from files. Files can be opened using the built-in function open. Using a with as syntax (called a ‘Context Manager’) makes using open and getting a handle for the file super easy:

with open('somefile.txt', 'r') as fileobj:

write code here using fileobj

This ensures that when code execution leaves the block the file is automatically closed.

Files can be opened in different modes. In the above example the file is opened as read-only. To open an existing file for reading only use r. If you want to read that file as bytes use rb. To append data to an existing file use a. Use w to create a file or overwrite any existing files of the same name. You can use r+ to open a file for both reading and writing. The first argument of open() is the filename, the second is the mode. If mode is left blank, it will default to r.

let’s create an example file:

with open('shoppinglist.txt', 'w') as fileobj:
fileobj.write('tomato\npasta\ngarlic')
with open('shoppinglist.txt', 'r') as fileobj:
this method makes a list where each line
of the file is an element in the list lines = fileobj.readlines()
print(lines)

[‘tomato\n’, ‘pasta\n’, ‘garlic’]

with open('shoppinglist.txt', 'r') as fileobj:

GoalKicker.com – Python® Notes for Professionals 160

here we read the whole content into one string: content = fileobj.read()
get a list of lines, just like int the previous example: lines = content.split(‘\n’)
print(lines)

[‘tomato’, ‘pasta’, ‘garlic’]

If the size of the file is tiny, it is safe to read the whole file contents into memory. If the file is very large it is often better to read line-by-line or by chunks, and process the input in the same loop. To do that:

with open('shoppinglist.txt', 'r') as fileobj:
this method reads line by line: lines = []
for line in fileobj: lines.append(line.strip())

When reading files, be aware of the operating system-specific line-break characters. Although for line in fileobj automatically strips them off, it is always safe to call strip() on the lines read, as it is shown above.

Opened files (fileobj in the above examples) always point to a specific location in the file. When they are first opened the file handle points to the very beginning of the file, which is the position 0. The file handle can display its current position with tell:

fileobj = open('shoppinglist.txt', 'r')
pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 0.

Upon reading all the content, the file handler’s position will be pointed at the end of the file:

content = fileobj.read()
end = fileobj.tell()
print('This file was %u characters long.' % end)
This file was 22 characters long. fileobj.close()

The file handler position can be set to whatever is needed:

fileobj = open('shoppinglist.txt', 'r')
fileobj.seek(7)
pos = fileobj.tell()
print('We are at character #%u.' % pos)

You can also read any length from the file content during a given call. To do this pass an argument for read(). When read() is called with no argument it will read until the end of the file. If you pass an argument it will read that number of bytes or characters, depending on the mode (rb and r respectively):

reads the next 4 characters
starting at the current position next4 = fileobj.read(4)
what we got?
print(next4) # 'cucu'
where we are now? pos = fileobj.tell()
print('We are at %u.' % pos) # We are at 11, as we was at 7, and read 4 chars.
fileobj.close()

To demonstrate the difference between characters and bytes:

with open('shoppinglist.txt', 'r') as fileobj:
print(type(fileobj.read())) #
with open('shoppinglist.txt', 'rb') as fileobj:
print(type(fileobj.read())) #

Basic Input and Output: Read from stdin

Python programs can read from unix pipelines. Here is a simple example how to read from stdin:

import sys
for line in sys.stdin:
print(line)

Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended.

You can now pipe the output of another program into your python program as follows:

$ cat myfile | python myprogram.py

In this example cat myfile can be any unix command that outputs to stdout.

Alternatively, using the fileinput module can come in handy:

import fileinput
for line in fileinput.input():
process(line)

Basic Input and Output: Using input() and raw_input()

Python 2.x Version ≥ 2.3

raw_input will wait for the user to enter text and then return the result as a string.

foo = raw_input("Put a message here that asks the user for input")

In the above example foo will store whatever input the user provides.

Python 3.x Version ≥ 3.0

input will wait for the user to enter text and then return the result as a string.

foo = input("Put a message here that asks the user for input")

In the above example foo will store whatever input the user provides.

Basic Input and Output: Function to prompt user for a number

def input_number(msg, err_msg=None):
while True:
try:
return float(raw_input(msg))
except ValueError:
if err_msg is not None:
print(err_msg)
def input_number(msg, err_msg=None):
while True:
try:
return float(input(msg))
except ValueError:
if err_msg is not None:
print(err_msg)
And to use it:
user_number = input_number("input a number: ", "that's not a number!")
Or, if you do not want an "error message":
user_number = input_number("input a number: ")

Basic Input and Output: Printing a string without a newline at the end

Python 2.x Version ≥ 2.3

In Python 2.x, to continue a line with print, end the print statement with a comma. It will automatically add a space.

print "Hello,",
print "World!"
Hello, World!

Python 3.x Version ≥ 3.0

In Python 3.x, the print function has an optional end parameter that is what it prints at the end of the given string.

By default it’s a newline character, so equivalent to this:

print("Hello, ", end="\n")
print("World!")
Hello,
World!

But you could pass in other strings

print("Hello, ", end="")
print("World!")

Hello, World!

print("Hello, ", end="
")
print("World!")

Hello,
World!

print("Hello, ", end="BREAK")
print("World!")

Hello, BREAKWorld!

If you want more control over the output, you can use sys.stdout.write:

import sys
sys.stdout.write("Hello, ")
sys.stdout.write("World!")

Hello, World!

Learn More

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python setup.py TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment