Using the print function
Python 3.x Version ≥ 3.0
In Python 3, print functionality is in the form of a function
Input from a File
Input can also be read from files. Files can be opened using the built-in function open. Using a with <command> as <name> 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: