Python basis - Input and Output

Sometimes your program will have to interact with the user. For example, you'll want to get the contents of the user input, and to print out some of the results returned by the user. We can respectively input()function and printto fulfill the demand function.

For input, we can also use stra variety of methods (String, String) class. For example, you can use the rjustmethod to obtain a width of a right-aligned to the specified string. You can look help(str)for more details.

Another common type of input and output files are processed. Create, read and write files in most programs it is essential to the function, and we will explore this aspect in this chapter.

1. user input

Save the following program is io_input.py:

def reverse(text):
    return text[::-1]


def is_palindrome(text):
    return text == reverse(text)


something = input("Enter text: ")
if is_palindrome(something):
    print("Yes, it is a palindrome")
else:
    print("No, it is not a palindrome")

Output:

$ 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

We use the slicing feature flip text. We already know we can use seq[a:b]from the position astart to position bend to slicing sequence . We can also provide third parameter to determine the slice step (the Step) . The default step is 1, it will return a continuous text. Given a negative step, such as -1the return flip through text.

input()Function can take a string as an argument, and to show it to the user. Later it will wait for user input or hitting the return key. Once the user inputs something and Qiaoxia return key, input()the function returns the text entered by the user.

We get text and flip. If the text of the original text and the reverse same as the present, it is determined that the text is a palindrome .

+ Exercise

To check whether the text is part of the palindrome need to ignore punctuation, spaces and case of them. For example, "Rise to vote, sir." Palindrome is a piece of text, but our current program does not think so. You can improve the above program to recognize this palindrome enable it to do?

If you need some tips, then here you have an idea ......

2. File

You can create a part of fileand the appropriate use of its object class read, readline, writemethod to open or use the file, and they read or write. The ability to read or write files depends on the manner in which you specify to open the file. Finally, when you finished files, you can call the closemethod to tell Python we have completed the use of the file.

Case (save as io_using_file.py):

poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''

# 打开文件以编辑('w'riting)
f = open('poem.txt', 'w')
# 向文件中编写文本
f.write(poem)
# 关闭文件
f.close()

# 如果没有特别指定,
# 将假定启用默认的阅读('r'ead)模式
f = open('poem.txt')
while True:
    line = f.readline()
    # 零长度指示 EOF
    if len(line) == 0:
        break
    # 每行(`line`)的末尾
    # 都已经有了换行符
    #因为它是从一个文件中进行读取的
    print(line, end='')
# 关闭文件
f.close()

Output:

$ python3 io_using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!

First, we use the built-in openfunction and specify the file name, and we want to use to open a file open mode. Open mode can be a read mode 'r'( ), write mode ( 'w') and append mode 'a'( ). We can also choose to be by text mode ( 't') or binary mode ( 'b'to read), write or append text. In fact there are other more modes are available, help(open)will give you more details about them. By default, open()it will be treated as a text file ( t EXT) file, and to read ( r open it ead) mode.

In our case, we first open the file using write mode and use the file object's writemethods to write to a file, and finally through closeclose the file.

Next, we re-open the same file in read mode. We do not need a pattern specified as "read the text file" is the default. We used in a loop readlineto read each line of the file method. This approach will complete a series of rows, where the end of the line also includes a line break. When an empty string is returned, it means that we have reached the end of the file, and through breakexit the loop.
Finally, we closeclose the file.

Now, you can check the poem.txtcontents of the file to confirm the program does this file for write and read operations.

3. Pickle

Called Python provides a Picklestandard module, through which you can in any store pure Python object to a file and later to retrieve it. This is called * permanently (Persistently) * storage object.

Case (save as io_pickle.py):

import pickle

# 我们存储相关对象的文件的名称
shoplistfile = 'shoplist.data'
# 需要购买的物品清单
shoplist = ['apple', 'mango', 'carrot']

# 准备写入文件
f = open(shoplistfile, 'wb')
# 转储对象至文件
pickle.dump(shoplist, f)
f.close()

# 清除 shoplist 变量
del shoplist

# 重新打开存储文件
f = open(shoplistfile, 'rb')
# 从文件中载入对象
storedlist = pickle.load(f)
print(storedlist)

Output:

$ python io_pickle.py
['apple', 'mango', 'carrot']

To store an object in a file, we first need opento write ( w Rite) binary ( b inary) mode to open the file, and then call the picklemodule's dumpfunctions. This process is called encapsulation (Pickling) .

Next, we pass picklethe module loadreceiving the returned object function. This process is called unpacking (unpickling) .

4. Unicode

Up to now, when we write or use a string, read or write a file, we use only plain English characters.

Note: If you are using Python 2, we hope to be able to read and write other non-English languages, we need to use the unicodetype that all the letters uat the beginning, for example u"hello world".

>>> "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 wish to communicate while other computers on the Internet and we need our Unicodestring can be converted to a transmission and reception format, which is called "UTF-8". We can read and write in this format, just use a simple keyword arguments to our standard openfunctions:

# 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)

Now you can ignore the importstatement, we will be in chapters module to explore more details about its chapters.

Whenever we use Unicode literals remarks such as writing a program above, we must ensure that the Python program has been told that we are using UTF-8, so we have to # encoding=utf-8the comments placed on top of our program.

We use io.openand provides a "coding (Encoding)" and "decoding (Decoding)" parameter to tell Python that we are using Unicode.

to sum up

We have discussed about the various types of input and output such content file handling, as well as about the pickle module on Unicode.

Next, we will explore some unusual concepts.

Resources

[1] input and output · Byte of Python

Published 66 original articles · won praise 101 · views 30000 +

Guess you like

Origin blog.csdn.net/u010705932/article/details/104418053