详细讲解io 配合代码
时间: 2023-07-30 20:11:42 浏览: 52
IO(Input/Output)是计算机系统中非常重要的一个概念,它指的是计算机与外界设备或存储介质之间的数据交互。在编程中,我们经常需要读取文件、网络数据、用户输入等信息,或者将计算结果输出到文件、屏幕、网络等地方,这些都需要使用IO操作。
下面以 Python 为例,简单讲解如何进行IO操作。
### 文件IO
Python 提供了 `open()` 函数来打开一个文件,并返回一个文件对象。我们可以使用该对象来读取或写入文件。
```python
# 打开文件
file = open("test.txt", "r")
# 读取文件内容
content = file.read()
# 关闭文件
file.close()
# 打印文件内容
print(content)
```
在打开文件时,我们可以指定打开模式:
- `'r'`:只读模式,文件指针放在文件开头;
- `'w'`:写入模式,如果文件已存在,先清空文件内容,再写入新内容;如果文件不存在,则创建文件并写入内容;
- `'a'`:追加模式,如果文件已存在,在文件末尾追加新内容;如果文件不存在,则创建文件并写入内容。
```python
# 写入文件
file = open("test.txt", "w")
file.write("Hello, world!")
file.close()
# 追加文件
file = open("test.txt", "a")
file.write("\nThis is a test.")
file.close()
```
### 标准IO
Python 中的标准IO包括 `sys.stdin`、`sys.stdout` 和 `sys.stderr`,它们分别代表标准输入、标准输出和标准错误输出。我们可以通过这些对象来读取用户输入和输出计算结果。
```python
# 读取用户输入
name = input("Please enter your name: ")
print("Hello, " + name)
# 输出计算结果
result = 1 + 2
print("1 + 2 = ", result)
```
### 网络IO
Python 中的 `socket` 模块提供了网络IO功能,我们可以使用它来进行网络通信。下面是一个简单的示例,该示例创建了一个服务器程序,监听端口号为 8888,当客户端连接时,向客户端发送一条消息,并关闭连接。
```python
import socket
# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定地址和端口号
server_socket.bind(('localhost', 8888))
# 监听端口号
server_socket.listen(5)
while True:
# 等待客户端连接
client_socket, addr = server_socket.accept()
print('connection from', addr)
# 向客户端发送消息
client_socket.send(b'Hello, world!')
# 关闭连接
client_socket.close()
```
客户端程序可以使用 `socket` 模块的 `socket.connect()` 方法来连接服务器,然后使用 `socket.recv()` 方法来接收服务器发送的消息。
```python
import socket
# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
client_socket.connect(('localhost', 8888))
# 接收服务器发送的消息
message = client_socket.recv(1024)
# 打印消息内容
print(message.decode())
# 关闭连接
client_socket.close()
```
以上是 Python 中常见的IO操作,通过使用这些IO函数和对象,我们可以方便地进行文件读写、标准IO和网络IO操作。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)