(8) A Byte of Python: Input and Output

Posted by phprock on Tue, 14 May 2019 21:09:22 +0200

If you want to get the user's input and print some returned results to the user. We can achieve this requirement through the input() function and the print function, respectively. For input, we can also use various methods of the str (String, String) class. Another common input and output type is processing files.

1. User input content

def reverse(text):
    return text[::-1]   #Content reversal
def is_palindrome(text):
    return text == reverse(text)
something = input("Enter text: ")
if is_palindrome(something):   #Judging whether it is palindrome
    print("Yes, it is a palindrome")
else:
    print("No, it is not a palindrome")
$ python3 io_input.py
Enter text: sir
No, it is not a palindrome
$ python3 io_input.py
Enter text: madam
Yes, it is a palindrome
$ python3 io_input.py
Enter text: racecar
Yes, it is a palindrome
2. document

You can open or use files and read or write them by creating an object belonging to the file class and using its read, readline, and write methods appropriately. The ability to read or write files depends on how you specify to open them. Once the file is complete, you can call close to tell Python that the file is used.

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''
# Open the file to edit('w'riting)
f = open('poem.txt', 'w')
# Write text to a document
f.write(poem)
# Close file
f.close()
# If no special designation is made,
# It is assumed that default reading is enabled('r'ead) Pattern
f = open('poem.txt')
while True:
    line = f.readline()
    # Zero Length Indicator EOF
    if len(line) == 0:
        break
    # The end of each line (`line')
    # All have line breaks.
    #Because it is read from a file
    print(line, end='')
# Close file
f.close()
$ python3 io_using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Open mode can be read mode ('r'), write mode ('w') and add mode ('a'). We can also choose to read, write, or append text through text mode ('t') or binary mode ('b'). By default, open() treats the file as a text file and opens it in read mode.

3. Pickle

Store any pure Python object in a file and retrieve it later. This is called Persistently stored objects.

import pickle
# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()
# Destroy the shoplist variable
del shoplist
# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)
$ python io_pickle.py
['apple', 'mango', 'carrot']
To store an object in a file, we first need to open the file in write binary mode through open, and then call the dump function of the pickle module. This process is called Pickling. Next, we receive the returned object through the load function of the pickle module. This process is called Unpickling.

4. Unicode

>>> "hello world"
'hello world'
>>> type("hello world")
<class 'str'>
>>> u"hello world"
'hello world'
>>> type(u"hello world")
<class 'str'>

When we read or write a file or when we want to communicate with other computers on the Internet, we need to convert our Unicode string to a format that can be sent and received, called UTF-8. We can read and write in this format, using only a simple keyword parameter to our standard open function.

# encoding=utf-8
import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text)
Whenever we write a program using Unicode literals like the one above, we have to make sure that the Python program has been told that we are using UTF-8, so we have to release the # encoding=urf-8 annotation at the top of our program. We use io.open and provide "Encoding" and "Decoding" parameters to tell Python that we are using Unicode.




Topics: Python encoding Programming