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.
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("不是回文")
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.
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()
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.
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”.
- Pyyaml tutorial introduction to pyyaml library and YML writing and reading
- An introduction to sys modules in Python and how packages are imported and used
- Python USES the PO design pattern for automated testing
- Python: How to Encode the File (including HTML, TXT, Doc, etc.)
- The Python DOM method iterates over all the XML in a folder
- python3 ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833) Error
- Python recursively traverses all files in the directory to find the specified file
- Error reading file by pandas pandas.errors.EmptyDataError: no columns to parse from file
- Python asynchronous execution library asyncio
- Python classes that connect to the database
- Python: ___ () vs ___ str__()
- Python: How to Create an Automatic Recording Program
- [How to Solve] Python TypeError: ‘int‘ object is not subscriptable
- Python raspberry pie starts sending IP address to mailbox
- Python 3.X error: valueerror: data type must provide an itemsize
- Extracting Data from XML (Using Python to Access Web Data)
- Gunicorn Flask Error: [ERROR] Socket error processing request
- Python: How to parses HTML, extracts data, and generates word documents
- Full explanation of SYS module of Python
- Autograd error in Python: runtimeerror: grad can be implicitly created only for scalar outputs