Loading

python中的io操作

以下是 Python 中 I/O 操作的一些示例:

一、文件输入输出

  1. 写入文件:
# 打开文件以写入模式,如果文件不存在则创建
with open('output.txt', 'w') as f:
    f.write('Hello, world!')
  1. 读取文件:
# 打开文件以读取模式
with open('input.txt', 'r') as f:
    content = f.read()
    print(content)

二、标准输入输出

  1. 从标准输入读取:
name = input("请输入你的名字:")
print(f"你好,{name}!")
  1. 打印到标准输出:
print("这是一条输出信息。")

三、网络 I/O(以简单的 HTTP 请求为例)

使用 requests 库进行网络请求,这也是一种输入输出操作,从网络获取数据(输入)并可能将数据保存或处理(输出)。

import requests

response = requests.get('https://www.example.com')
print(response.text)

这些示例展示了 Python 中不同类型的 I/O 操作,包括文件读写、用户交互和网络请求。

posted @ 2024-11-29 18:27  一只大学生  阅读(41)  评论(0)    收藏  举报