python: File Processing and Input and Output

Sometimes your program will interact with the user. For example, you would want to get the user’s input and print out some returned results to the user. We can achieve this requirement through input() function and print function respectively.

For input, we can also use various methods of the str (String) class. For example, you can use the rjust method to get a string that is right-justified to a specified width. You can check help(str) for more details.

Another common type of input and output is processing files. Creating, reading, and writing files are essential functions for many programs , and we will explore this aspect in this chapter.

User input

Save the following program as io_input.py:

def reverse(text): 
    return text[::-1] 
def is_backtext(text): 
    return text == reverse(text) 
something = input("请输入文字: ") 
if is_backtext(something): 
    print("是回文") 
else:
    print("不是回文")

Output:

python io_input.py
输入文字: abc
不是回文

python io_input.py
输入文字: moom
是回文

 

We use the slice function to flip the text. We have learned that we can slice a sequence from the beginning of position a to the end of position b by using seq[a:b]. We can also provide a third parameter to determine the step size of the slice (Step). The default step size is 1, it will return a continuous text. If a negative step size is given, such as -1, the flipped text will be returned.

The input() function can accept a string as a parameter and display it to the user. After that, it will wait for the user to input content or hit the return key. Once the user enters something and hits the return key, the input() function will return the text entered by the user.

We get the text and flip it. If the original text is the same as the flipped text, it is judged that this text is a palindrome.

file

You can open or use files by creating an object belonging to the file class and using its read, readline, and write methods appropriately , and read or write them. The ability to read or write files depends on how you specify to open the file. Finally, when you have finished the file, you can call the close method to tell Python that we have finished using the file.

Example (save as io_using_file.py):

poem = '''编程是很有趣的事件,
如果你想让你的工作也变得有趣的话:
使用Python!'''

# 打开文件以编辑('w'riting) 
f = open('poem.txt', 'w',encoding='utf-8') 
# 向文件中编写文本 
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:

python io_using_file.py
编程是很有趣的事件,
如果你想让你的工作也变得有趣的话:
使用Python!

How it works

First, we use the built-in open function and specify the file name and the open mode we want to use to open a file.

The open mode can be read mode (‘r’), write mode (‘w’) and append mode (‘a’).

We can also choose whether to read, write or append text in text mode (‘t’) or binary mode (‘b’ ). There are actually more modes available, help(open) will give you more details about them.

By default, open() treats the file as a text file and opens it in read mode .

In our case, we first open the file in write mode and use the write method of the file object to write the file, and finally close the file with close.

Next, we reopen the same file in reading mode. We don’t need to specify a certain mode, because “read text file” is the default. We use the readline method in the loop to read each line of the file. This method will be a complete line, which also contains a newline at the end of the line. When an empty string returns, it means that we have reached the end of the file and exit the loop with break

Finally, we finally closed the file with close. Now, you can check the content of the poem.txt file to confirm that the program has indeed written and read the file.

encoding=utf-8

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. This format is called == “UTF- 8″==. We can read and write in this format, just use a simple keyword parameter to our standard open function: encoding=’utf-8′

Unicode has multiple translations such as “Unicode”, “Universal Code” and “International Code”.

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *