Input and Output #
WHAT is this? #
My version: #
Input and output in Python refer to how a program receives data (input) and how it displays or saves data (output).
You can print data to the screen for users to see or write it to files for later use.
WHY is this important? #
My version: #
- User interaction: It allows programs to interact with users by receiving input and providing feedback;
- Data persistance: Writing data to files enables you to save information for future use, making your programs more useful and efficient; and
- Data processing: Many applications require reading data from files, processing it, and then outputting results.
WHY should I learn this? #
My version: #
- Essential skill: It’s a fundamental part of programming that you will use in almost every project;
- Enhances functionality: Knowing how to handle input and output allows you to create more interactive and useful applications; and
- Real-world application: Many real-world applications involve reading from and writing to files, making this knowledge applicable in various scenarios.
WHEN will I need this? #
My version: #
- Building user interface: When creating programs that require user input or display results;
- Data management: When you need to save data to files or read data from files for processing; and
- Developing application: In any application that requires interaction with users or data storage.
HOW does this work? #
fancier output formatting #
In Python, there are several ways to format output beyond simple printing. Here are the main methods:
string literals (f-string):
Start a string with f
or F
to include expressions inside curly braces {}
.
>>> year = 2024
>>> event = 'Referendum'
>>> print(f'Results of the {year} {event}')
Results of the 2024 Referendum
>>> print(F'Results of the {year} {event}')
Results of the 2024 Referendum
str.format()
method:
Use the str.format()
method to format strings with placeholders {}
and provide values to substitute.
You can also specify formatting options, such as padding and percentage.
>>> yes_votes = 42_572_654
>>> total_votes = 85_705_149
>>> percentage = yes_votes / total_votes
>>> print('{:-9} YES votes {:2.2%}'.format(yes_votes, percentage))
42572654 YES votes 49.67%
string concatenation and slicing:
You can manually format strings using concatenation and slicing to create custom layouts.
>>> first_name = "John"
>>> last_name = "Doe"
>>> full_name = first_name + " " + last_name
>>> print(full_name)
John Doe
>>> text = "Hello, world!"
>>> substring = text[7:12]
>>> print(substring)
world
debugging with str() and repr():
Use str()
for a human-readable representation and repr()
for a representation that can be read by the interpreter.
>>> s = 'Hello, world.'
>>> print(str(s))
Hello, world.
>>> print(repr(s))
'Hello, world.'
template class:
The string module includes a Template
class that allows for simple value substitution using placeholders like $x
, but it offers less control over formatting.
>>> from string import Template
>>> template_string = Template("Hello, $name! You have $count new messages.")
>>> result = template_string.substitute(name="Alice", count=5)
>>> print(result)
Hello, Alice! You have 5 new messages.
>>> result_safe = template_string.safe_substitute(name="Bob")
>>> print(result_safe)
Hello, Bob! You have $count new messages.
reading and writing files #
In Python, you can read from and write to files using the open()
function, which returns a file object. The basic syntax is:
f = open(filename, mode, encoding=None)
arguments:
- filename: A string containing the name of the file.
- mode: A string that specifies how the file will be used:
- ‘r’: Read (default mode).
- ‘w’: Write (overwrites existing file).
- ‘a’: Append (adds data to the end of the file).
- ‘r+’: Read and write.
- encoding: Specifies the character encoding (recommended:
encoding="utf-8"
).
text vs. binary mode:
- Files are opened in text mode by default, which handles string data and converts line endings.
- Binary mode (by appending ‘b’ to the mode) reads and writes data as bytes, without any encoding. No encoding can be specified in binary mode.
using the with
statement:
It is best practice to use the with
statement when working with files. This ensures that the file is properly closed after its block is executed, even if an error occurs.
>>> with open('workfile', encoding="utf-8") as f:
>>> read_data = f.read()
After the with
block, the file is automatically closed:
f.closed # Output: True
closing files:
If not using with
, you must manually close the file using f.close()
. Failing to do so may result in incomplete writes to disk.
>>> f.close()
error handling:
After a file is closed, any attempt to read or write will raise an error:
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
methods of file objects #
File objects in Python provide various methods for reading from and writing to files. Here’s an overview of the key methods:
reading from files:
f.read(size)
: Reads up to size characters (in text mode) or bytes (in binary mode) from the file. If size is omitted or negative, it reads the entire file.
f.readline()
: Reads a single line from the file, including the newline character at the end. Returns an empty string when the end of the file is reached.
looping over the file:
You can iterate over the file object to read lines efficiently.
>>> for line in f:
>>> print(line, end='')
f.readlines()
: Reads all lines from the file and returns them as a list.
writing to files:
f.write(string)
: Writes the contents of string to the file and returns the number of characters written.
Other objects must be converted to a string or bytes before writing.
file positioning:
f.tell()
: Returns the current position in the file (in bytes for binary mode).
f.seek(offset, whence)
: Changes the file position. offset
is added to a reference point defined by whence
:
- 0: Beginning of the file (default).
- 1: Current position.
- 2: End of the file.
additional methods:
isatty()
: Checks if the file is connected to a terminal.
truncate(size)
: Resizes the file to the given size.
Important Notes:
- In text mode, seeking is limited to the beginning of the file, and only offsets returned by
f.tell()
or zero are valid. - Always ensure to close the file or use the with statement to manage file resources properly.
saving structured data with json
#
Python provides a convenient way to save and read structured data using the JSON (JavaScript Object Notation) format, which is widely used for data interchange.
The json
module in Python allows for easy serialization and deserialization of complex data types like nested lists and dictionaries.
serialization and deserialization:
- Serialization: Converting Python data structures (like lists and dictionaries) into a JSON string representation. This is done using
json.dumps()
.
>>> import json
>>> x = [1, 'simple', 'list']
>>> json_string = json.dumps(x)
>>> print(repr(json_string))
'[1, "simple", "list"]'
- Deserialization: Converting a JSON string back into a Python object using
json.loads()
or reading from a file withjson.load()
.
writing to and reading from files:
To write a Python object to a file in JSON format, use json.dump()
. This function serializes the object and writes it directly to a file.
>>> data = {'glossary': {'title': 'example glossary', 'GlossDiv': {'title': 'S', 'GlossList': {'GlossEntry': {'ID': 'SGML', 'SortAs': 'SGML', 'GlossTerm': 'Standard Generalized Markup Language', 'Acronym': 'SGML', 'Abbrev': 'ISO 8879:1986', 'GlossDef': {'para': 'A meta-markup language, used to create markup languages such as DocBook.', 'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}}}
>>> with open('data.json', 'w', encoding='utf-8') as f:
... json.dump(data, f)
To read a JSON object from a file, use json.load()
.
>>> with open('data.json', 'w', encoding='utf-8') as f:
... json.dump(data, f)
...
>>> with open('data.json', 'r', encoding='utf-8') as f:
... x = json.load(f)
...
>>> print(x)
{'glossary': {'title': 'example glossary', 'GlossDiv': {'title': 'S', 'GlossList': {'GlossEntry': {'ID': 'SGML', 'SortAs': 'SGML', 'GlossTerm': 'Standard Generalized Markup Language', 'Acronym': 'SGML', 'Abbrev': 'ISO 8879:1986', 'GlossDef': {'para': 'A meta-markup language, used to create markup languages such as DocBook.', 'GlossSeeAlso': ['GML', 'XML']}, 'GlossSee': 'markup'}}}}}
In summary, the json
module in Python simplifies the process of saving and loading structured data, making it easy to work with complex data types in a format that is widely recognized and used in modern applications.