python运维1

元组

bash 复制代码
元组是一组有序的不可变的元素集合,一旦创建,元组中元素的个数不能被修改,这种特性使得元组适用于存储那些不希望被该的数据

列子:
假设你在开发一个电商网站,你需要记录每个产品的基本信息,比如产品的ID,名称和价格,这些数据是固定的,不应该被随意篡改,你可以使用元组来存储这些信息,
例:一个产品的信息可以代表一个元组
product = (12345,"智能手机",299.99)
在这个元组中:
   12345 是这个产品的ID
   智能手机是这个产品的名称
   299.99是这个产品的价格
  这些产品一旦录入系统后,不应该被修改,因为他代表了产品的基本属性
  

为什么要用元组?

bash 复制代码
元组用于那些存储不需要被修改的数据,这种不可变性可以防止意外发生,并确保数据的一致性,在实际项目中,使用元组可以帮助保护数据的完整性

示例:
假设你的电商网站有一个配置文件,记录了每个订单的状态,如 待支付,已发货、已完成等,这些状态在定义后不应该被修改,所以使用元组来存储他们最合适

order_statuses=("待支付","已发货","已完成")

这些状态是固定的,因此使用元组来保存这些状态可以防止程序在运行过程中意外的修改这些数据的状态值,从而确保订单的正确性



编写代码
1.创建含有产品信息的元组
首先,我们定义一个产品的元组,并展示如何访问和使用这些数据


import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') #对字符集进行转换,转成utf8形式,这样控制台的中文不会乱码

# 定义一个产品的元组
product = (1234,"智能手机",299.99)

#打印产品的信息
product_id,product_name,product_price  = product
print(f"产品的ID {product_id}")
print(f"产品的名称 {product_name}")
print(f"产品的价格 {product_price}")
运行代码
root@ubuntu0:~# /usr/bin/python3 /root/3.py
产品的ID 1234
产品的名称 智能手机
产品的价格 299.99


import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

# 定义一个产品的元组
product = (1234,"智能手机",299.99)

#打印产品的信息
product_id,product_name,product_price  = product
print(f"产品的ID {product_id}")
print(f"产品的名称 {product_name}")
print(f"产品的价格 {product_price}")

#尝试修改产品的价格
product[1] = "高端智能手机"
print(product)
运行代码,可以产出元组不允许修改
root@ubuntu0:~# /usr/bin/python3 /root/3.py
产品的ID 1234
产品的名称 智能手机
产品的价格 299.99
Traceback (most recent call last):
  File "/root/3.py", line 15, in <module>
    product[1] = "高端智能手机"
TypeError: 'tuple' object does not support item assignment



创建订单状态
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stderr.buffer,encoding="utf-8")

order_status = ("已发货","待支付","已付款")
print("订单状态列表")
print("状态1",order_status[0])
print("状态2",order_status[1])
print("状态3",order_status[2])
root@ubuntu0:~# /usr/bin/python3 /root/4.py
订单状态列表
状态1 已发货
状态2 待支付
状态3 已付款

案例:在地理信息系统中(GIS)或者地图应用中,地理坐标(经度和维度)通常作为元组存储,因为这些坐标在记录时是固定的。不需要修改

字典

bash 复制代码
字典是一种无序的、键值对形式的容器,可以把字典想象成一个由钥匙和钥匙对应的锁组成的集合


举个例子:
假设你是一个学校的班主任,需要管理班中每个学生的电话号码,你可以用字典来存储这些信息,其中学生的名字作为键、电话号码作为值,比如
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

student_phonebook = {
  "小丽": "123456",
  "小红": "3456",
  "小绿": "5678"
}
xiaohong_student_phonebook = student_phonebook["小红"]
print(xiaohong_student_phonebook)
root@ubuntu0:~# /usr/bin/python3 /root/3.py
3456

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

library_books = {
 "978-7-111-12345-0": {
 "title": "活着",
 "author": "余华",
 "available": True
 },
 "978-7-5399-3788-2": {
 "title": "白夜行",
 "author": "东野圭吾",
 "available": False
 },
 "978-7-119-12087-0": {
 "title": "围城",
 "author": "钱钟书",
 "available": True
 }
}
# 取出978-7-5399-3788-2 的 available 字典的值
print(library_books["978-7-5399-3788-2"]["available"])
root@ubuntu0:~# /usr/bin/python3 /root/3.py
False

集合

bash 复制代码
集合是一种无序的、不重复的,他有点像数学中集合的概念,特别适合用于去重或者检查某个元素是否在集合中



例:
假设你正在管理一个公司的员工邮箱列表,因为有些员工可能会多次出现或者错误的被输入,你需要去重并确认所有的员工邮箱是否唯一,可以使用集合这一功能
举个例子:员工邮箱去重
假设你正在管理一个公司的员工邮箱列表。因为有些员工可能会多次出现或者错误地被输
入,你需要去重并确认所有员工邮箱都是唯一的。你可以使用集合来实现这一功能:

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

email_list = [
 "alice@example.com",
 "bob@example.com",
 "carol@example.com",
 "alice@example.com", # 重复的邮箱
 "dave@example.com",
 "bob@example.com" # 重复的邮箱
]
# 使用集合去重
unique_emails = set(email_list)
print(unique_emails)


import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

email_list = [
 "alice@example.com",
 "bob@example.com",
 "carol@example.com",
 "alice@example.com", # 重复的邮箱
 "dave@example.com",
 "bob@example.com" # 重复的邮箱
]
# 使用集合去重
unique_emails = set(email_list)
print(unique_emails)

# 检查一个邮箱是否在集合里面
email_to_check = "alice@example.com"
print(email_to_check in unique_emails)
{'alice@example.com', 'bob@example.com', 'dave@example.com', 'carol@example.com'}
True


案例 1:社交网络共同好友分析工具
假设你在社交网络上有两个用户,想要找出他们的共同好友。可以使用集合来实现这一功
能:
# 用户的好友列表
user_a_friends={"小明","小丽","小刚","小红"}
user_b_friends = {"小红", "小刚", "小李", "小张"}
# 找出共同好友,求交集
common_friends = user_a_friends.intersection(user_b_friends)
#备注:intersection 是集合操作中的一个方法,用于找出两个或多个集合的交集。交集是
指所有集合中都存在的元素
print("共同好友:", common_friends)
root@ubuntu0:~# /usr/bin/python3 /root/set.py
{'小刚', '小红'}


案例2 英语句子中单词的统计
假设我们有一段英文文本,想要统计每个单词出现的次数,我们可以使用collections.Counter
from  collections import Counter
#文本内容
text = "I love learning. learning is fun. I enjoy learning every day."
#将文本替换成小写,并替换标点符号为空格

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

from  collections import Counter
#文本内容
text = "I love learning. learning is fun. I enjoy learning every day."
#将文本替换成小写,并替换标点符号为空格
cleaned_text=text.lower().replace("."," ") #lower 将所有的大写替换为小写
#按空格分词
words=cleaned_text.split()

#统计每个单词出现的次数
print(Counter(words))
root@ubuntu0:~# /usr/bin/python3 /root/set.py
Counter({'learning': 3, 'i': 2, 'love': 1, 'is': 1, 'fun': 1, 'enjoy': 1, 'every': 1, 'day': 1})
root@ubuntu0:~# 

if语句

bash 复制代码
if条件:
	当条件为true时执行代码
基本结构
x=10
if x>5:
    print("x大于5")

if-else 语句
有时候我们需要在条件不成立的情况下执行另一段代码,我们可以用if-else语句
if 条件:
	当条件为True时执行代码
else:
	当条件为False时执行代码

x=3
if x>5:
	print("x大于5")
else:
	print("x小于5")


if-elif-else 语句
当有多个条件需要判断时,可以使用elif

if 条件1:
	#条件1成立执行此代码
elif 条件2:
   #条件2成立执行此代码
else:
   #都不成立执行此代码
示例:
x = 7
if x > 10:
 print("x 大于 10")
elif x > 5:
 print("x 大于 5 但小于或等于 10")
else:
 print("x 小于或等于 5")

条件语句的嵌套与组合
2.1 嵌套条件语句
条件语句可以嵌套使用,用来处理更加复杂的逻辑。
x = 20
y = 15
if x > 10:
  if y > 10:
      print("x 和 y 都大于 10")

2.2 逻辑运算符与条件语句组合
可以使用 and、or 和 not 等逻辑运算符来组合多个条件。
示例:
x = 8
y = 6
if x > 5 and y > 5:
 print("x 和 y 都大于 5")


在处理多个条件时,可以通过逻辑运算符 and、or 和 not 来组合条件。逻辑运算符用于控
制条件的组合方式,帮助实现更复杂的逻辑判断。
# 示例:复杂条件组合
x = 10
y = 20
z = 15
if x > 5 and y > 15 or z < 10:
 print("满足条件:x 大于 5 且 y 大于 15,或 z 小于 10")
else:
 print("条件不满足")
 在这个例子中,条件是由 and 和 or 运算符组合的,只有在 x 大于 5 且 y 大于 15,或者 z
小于 10 的情况下,条件才会成立


 短路逻辑
在 Python 中,and 和 or 运算符具有短路特性。当 Python 在评估一个逻辑表达式时,如果
已经可以确定整个表达式的值,它就会停止评估剩下的部分
# 示例:短路逻辑
x = 10
if x > 5 or x / 0 == 1:
 print("只要 x 大于 5,就不会执行后面的除法运算")
# 这个表达式中的除法运算不会被执行,因为 x > 5 为 True,`or`操作已经可以确定结果为
True。




条件表达式的简化
三元表达式
Python 支持在一行中写条件判断,这被称为三元表达式或条件表达式。它是 if-else 语句的
一种简化形式。
# 三元表达式
x = 10
result = "大于 5" if x > 5 else "小于或等于 5"
print(result)
这个例子展示了如何在一行中根据条件设置变量的值,三元表达式非常适合在简单判断时使用。
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

awer = input('请输入用户(admin|editor|viewer): ')
if awer == "admin":
    print('你具有管理权限')
elif awer == "editor":
    print ('你具有编辑权限')
elif awer == "viewer":
    print("你具有查看权限")




个人身份信息验证系统
验证以下内容:
1. 手机号:必须是 11 位数字。
2. 姓名:必须是 2 到 20 个汉字。
3. 身份证号:需要符合中国身份证号的格式(15 位或 18 位数字,或者含有字母 X 的18 位格式)。

for 循环

bash 复制代码
1. 循环语句
1.1 循环的定义
循环是指程序按照一定的规则重复执行某些操作。编程中常用的循环结构有 for 循环和
while 循环。它们主要区别在于循环的条件和控制方式。

1.2 循环的类型
• for 循环:适用于已知循环次数的场景。通过初始化、条件判断和表达式来控制循
环。
• while 循环:适用于循环次数未知,但有一个明确的终止条件的场景。循环会持续
执行直到条件不满足。


1.3 语法结构:
for variable in iterable:
 # 代码块
 #variable 是每次循环时的当前值。
# iterable 是一个可以迭代的对象(如列表、字典等)。
示例:
for i in range(5):
 print(i)
这段代码将打印 0 到 4 的数字。

while 循环

bash 复制代码
语法结构:
while condition:
 # 代码块
#condition 是一个布尔表达式。当其值为 True 时,循环继续执行;当其值为 False 时,循
环终止。
i = 0
while i < 5:
 print(i)
 i += 1 #i=i+1
#这段代码同样将打印 0 到 4 的数字。

运维相关的案列

bash 复制代码
 1.批量数据备份与恢复
 假设我们需要对Linux文件进行操作,例如备份,具体案列如下
 root@ubuntu0:~# mkdir -p /path/to/config/files/
root@ubuntu0:~# mkdir -p /path/to/backup
root@ubuntu0:~# touch  /path/to/config/files/server{1..3}.conf
root@ubuntu0:~# ll /path/to/config/files/server
server1.conf  server2.conf  server3.conf
root@ubuntu0:~# echo 111 > /path/to/config/files/server1.conf


import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 

import os
#导入 Python 的 os 模块,提供与操作系统交互的功能,如文件和目录操作。
import shutil
#提供高级文件操作功能,如复制文件。

# 假设有一个包含服务器配置文件的目录
config_dir = '/path/to/config/files/'
#服务器配置文件的目录的路径。
backup_dir = '/path/to/backup'
#备份文件将被存储的目录的路径。

# 遍历目录中的每一个文件,以列表的形式输出
for filename in os.listdir(config_dir):
    #我只想要/path/to/config/files/路径下的.conf结尾的文件
    if filename.endswith('.conf'):
        #如果是.conf结尾的,那我要把文件完整的目录获取到 os.path获取完整的路径
        #join方法对文件进行拼接,config_dir = '/path/to/config/files/' 
        #os.path.join(拼接路径,对那些文件进行拼接)
        file_path = os.path.join(config_dir,filename)
        #对备份路径进行拼接
        back_path = os.path.join(backup_dir,filename)
        #进行备份操作
        shutil.copy(file_path,back_path)
        print(f"backup of {filename} over")
    

验证
root@ubuntu0:~# cat /path/to/backup/server1.conf
111


2.旧日志数据的清理与管理
root@ubuntu0:~# mkdir -p /path/to/logs
root@ubuntu0:~# touch /path/to/logs/logs{1..3}.log
root@ubuntu0:~# ll /path/to/logs/
total 8
drwxr-xr-x 2 root root 4096 May  5 11:21 ./
drwxr-xr-x 5 root root 4096 May  5 11:20 ../
-rw-r--r-- 1 root root    0 May  5 11:21 logs1.log
-rw-r--r-- 1 root root    0 May  5 11:21 logs2.log
-rw-r--r-- 1 root root    0 May  5 11:21 logs3.log
#模拟是60天前创建的
root@ubuntu0:~# touch -d '60 days ago' /path/to/logs/logs1.log
root@ubuntu0:~# ll /path/to/logs/logs1.log -d
-rw-r--r-- 1 root root 0 Mar  6 11:22 /path/to/logs/logs1.log
root@ubuntu0:~# touch -d '30 days ago' /path/to/logs/logs2.log

python脚本清理旧日志
删除30天之前的日志文件
import os
import time

#日志文件所在的目录
log_dir='/path/to/logs/'

#文件的最大保留天数
days_old=30

#获取当时间戳
current_time=time.time()

#获取目录下所有的文件
for filename in os.listdir(log_dir):
    #获取以.log结尾的文件
    if filename.endswith('.log'):
        #对日志文件做拼接
        file_path = os.path.join(log_dir,filename)
        #判断文件现在的时间和最后一次修改时间相减,是否大于30天如果大于,就删除
        #os.path.getmtime(file_path) 是获取file_path = os.path.join(log_dir,filename)所有的文件最后修改的时间
        file_age=current_time-os.path.getmtime(file_path)
        
        #判断如果大于30天则删除,time.time()获取出来的是秒,转换成天要 * 86400
        if file_age > days_old * 86400:
            os.remove(file_path)
            print(f"{filename} delete over")
root@ubuntu0:~# /usr/bin/python3 /root/set.py
logs2.log delete over
logs1.log delete over


定期的检查服务器的状态
import time
import subprocess
server = ['192.168.23.99','192.168.23.100','192.168.23.101']
for i in server:
    #[]中可以加参数也就是ping -c1  ,capture_output标准正确输出错误输出都要获取,text把抓取的对象转成字符串
    result=subprocess.run(["ping","-c","1",i],capture_output=True,text=True)
    print(f"Checking {i}")
    #标准正确输出
    print(f"stdout: {result.stdout}")
    #标准错误输出
    print(f"stderr: {result.stderr}")
    #输出状态码,0是正常 1是异常
    print(result.returncode)
root@ubuntu0:~# 
root@ubuntu0:~# /usr/bin/python3 /root/set.py
Checking192.168.23.99
stdout: PING 192.168.23.99 (192.168.23.99) 56(84) bytes of data.
64 bytes from 192.168.23.99: icmp_seq=1 ttl=64 time=0.229 ms

--- 192.168.23.99 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.229/0.229/0.229/0.000 ms

stderr: 
0
Checking192.168.23.100
stdout: PING 192.168.23.100 (192.168.23.100) 56(84) bytes of data.
From 192.168.23.99 icmp_seq=1 Destination Host Unreachable

--- 192.168.23.100 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms


stderr: 
1
Checking192.168.23.101
stdout: PING 192.168.23.101 (192.168.23.101) 56(84) bytes of data.
From 192.168.23.99 icmp_seq=1 Destination Host Unreachable

--- 192.168.23.101 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms


stderr: 
1



import time
import subprocess
server = ['192.168.23.99','192.168.23.100','192.168.23.101']
while True:
    for i in server:
        #[]中可以加参数也就是ping -c1  ,capture_output标准正确输出错误输出都要获取,text把抓取的对象转成字符串
        result=subprocess.run(["ping","-c","1",i],capture_output=True,text=True)
        print(f"Checking {i}")
        #标准正确输出
        print(f"stdout: {result.stdout}")
        #标准错误输出
        print(f"stderr: {result.stderr}")
        #输出状态码,0是正常 1是异常
        print(result.returncode)
        if result.returncode == 0:
            print(f"{server} is up")
        else:
            print(f"{server} is down")
    #每隔一天执行一次
    time.sleep(86400)

检测磁盘使用率
import shutil
import time
#设置时间间隔,单位s
CHECK_INTERVAL = 60
while True:
    #获取  / 磁盘使用情况
    total,used,free=shutil.disk_usage('/')
    usage_percent=(used/total) * 100
    print(f"DISK usage: {usage_percent: .2f}%")
    #每60s执行一次
    time.sleep(CHECK_INTERVAL)	
root@ubuntu0:~# /usr/bin/python3 /root/set.py
DISK usage:  50.82%



监控服务状态
import os
import time
#设置时间间隔,单位s
CHECK_INTERVAL = 60
#设置服务
SERVICES=['nginx']
while True:
    for service in SERVICES:
        #如果返回的是0就表示服务是正在运行的,反之则是异常
        status=os.system(f"systemctl is-active --quit {service}")
        if status !=0:
            os.system(f'systemctl start {service}')
            print(f'{service} is runing')
    time.sleep(CHECK_INTERVAL)  

在多台服务器上执行命令

python字符串相关的操作

bash 复制代码
用 ''  或者 "" 引起来的部分就是字符串
var1 = 'hello'
var2 = "hello"

root@ubuntu0:~# python3
Python 3.10.12 (main, Mar  3 2026, 11:56:32) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> var1 = 'hello'
>>> type(var1)
<class 'str'>
>>> var1[0]
'h'
>>> var1[1:3]   #左闭右开
'el'
>>>


python中字符串定义好了之后也不能随意更改,但是可以通过重新分配来更新字符串
var1=hello
var1=var1[:]+' world'  #var1[:]取出hello所有的字符


转义字符串
在python中表示一些特殊的字符 \n \t等
print('hello\nworld')
输出
hello
world

常见的转义符包括
\\   反斜杠符号
\'   单引号
\''  双引号
\n   换行
\t   水平制表符

字符串格式化

bash 复制代码
Python中使用 % 进行字符串格式化操作,在python中,%符号有两个常见的用途:
1.取模运算:用于计算两个数之间的余数
   例如:7%3的结果为1
2.字符串格式化符号,用于将变量的值插入到字符串指定位置,这种用法称为 旧式字符串格式化
   在这种情况下,%用于定义占位符,后面跟这一个格式化字符,用于指定变量的类型。例如:
   %s 表示插入一个字符串
   %d 表示插入一个整数
   %f 表示插入一个浮点数
   %% 表示插入一个百分符号本身
>>> name="alice"
>>> age=30
>>> print("my name is %s and I am %d years old") %(name,age)
my name is %s and I am %d years old

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
>>>
>>> print("my name is %s and I am %d years old" %(name,age))
my name is alice and I am 30 years old

字符串大小写转换

python 复制代码
首字母大写
>>> s='hello'
>>> print(s.capitalize())
Hello
>>>
>所有字母大写
>>> print(s.upper())
HELLO
字符串字母小写
>>> print(s.lower())
hello
字符串大小写反转
>>> print(s.swapcase())
HELLO
所有首字母大写
>>> s="hel;oo wadd"
>>> print(s.title())
Hel;Oo Wadd

Python文件处理

bash 复制代码
在python 中,文件操作是通过内置的open()函数来实现的,你可以使用不同的模式打开文件
如:
   r  只读模式
   w  写入模式(会覆盖原有内容)
   a  追加模式
操作完成之后必须关闭文件,,释放资源,pythoon提供了file.close()方法,也推荐是使用with语句,他会自动的关闭文件


使用with语句
with语句用于确保在代码执行完毕后,资源会被自动清理或关闭,即使在代码块中发生了异常,他简化了资源管理避免了显示关闭操作

with open('example.txt','r') as fiile:
	content = file.read() #读取整个文件
print(content)

读取文件: 可以选择读取整个文件的内容跟,逐行读取或者将文件内容读取到一个列表中,
    file.read(): 读取整个文件的内容
    for line in file:  逐行读取文件的内容
    file.readlines():   将所有行读入一个列表
写入文件: 可以选择覆盖原有内容或追加新内容
   file.write():  写入内容(覆盖原有的内容)
   file.writhlines(): 写入多行内容



1、file.read():一次性读取整个文件的内容,适用于文件较小,可以一次性加载到内存中
的场景。
•优点:操作简单,适合处理文件内容较小的情况。
•缺点:如果文件很大,可能会占用大量内存,因为整个文件内容都会被加载到内存
中。
适用场景:
•文件大小适中,能够完全载入内存时使用。
•当你需要对整个文件的内容进行处理或分析时使用。
2、for line in file:逐行读取文件的内容。file对象是一个可迭代对象,每次迭代返回一行
文本。
•优点:适合处理大文件,因为不会一次性将整个文件加载到内存中。逐行读取会将
当前行加载到内存,而不是整个文件。
•缺点:处理文件时,每次读取一行,可能会稍微增加处理时间
适用场景:
•文件较大时,逐行处理可以有效减少内存使用。
•你需要处理文件的每一行,可能会根据每行内容执行不同操作。
3、file.readlines():读取文件中的所有行,并将每一行作为列表中的一个元素返回。
•优点:能够在内存中以列表的形式处理文件的每一行,可以随机访问每一行。例如,
能够轻松地访问特定的行。
•缺点:会一次性将整个文件加载到内存中,因此适用于文件较小的情况。对于大文
件,可能会导致高内存使用。
适用场景:
•文件大小适中,能够完全载入内存时使用。
•需要多次访问文件中的不同部分或行时使用,因为你可以通过列表索引来访问特定
的行。


写入数据(覆盖模式):
#写入数据(覆盖原内容)
with open('example.txt', 'w') as file:
file.write("Hello, World!\n") #写入新的内容,覆盖原有内容
#重新读取文件内容
with open('example.txt', 'r') as file:
content = file.read()
print("File Content After Writing:")
print(content) #打印新内容

追加数据:
#追加数据到文件末尾
with open('example.txt', 'a') as file:
file.write("Appending a new line.\n") #追加新行到文件末尾
#重新读取文件内容
with open('example.txt', 'r') as file:
content = file.read()
print("File Content After Appending:")
print(content) #打印包含新追加内容的文件

with open('example.txt', 'a') as file:以追加模式打开文件(不会覆盖原有内容)。
file.write("Appending a new line.\n"):在文件末尾添加一行新内容。

写入多行:
#写入多行数据
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('example.txt', 'w') as file:
file.writelines(lines) #将列表中的多行写入文件
#重新读取文件内容
with open('example.txt', 'r') as file:
content = file.read()
print("File Content After Writing Lines:")
print(content) #打印新写入的多行内容
•file.writelines(lines):将列表lines中的每个元素(每行内容)写入文件。
相关推荐
盼小辉丶2 小时前
PyTorch深度学习实战(55)——在Android上部署PyTorch模型
android·pytorch·python·模型部署
yn002 小时前
Docker 一键部署加密支付网关:从零开始完整教程
运维·docker·容器
杨云龙UP2 小时前
Oracle CDB巡检脚本使用SOP:从HTML原始报告到Word正式交付_2026-05-29
运维·服务器·数据库·oracle·架构·html·巡检
難釋懷2 小时前
Nginx自签名-OpenSSL
运维·chrome·nginx
2301_803538952 小时前
CentOS版本差异详解和系统信息查看方法
linux·运维·centos
Cx330❀2 小时前
【Qt 核心机制篇】深度解析 Qt 信号与槽(Signals & Slots)机制:从底层原理、实战演练到 Lambda 进阶
linux·开发语言·c++·人工智能·qt·ubuntu
SunnyDays10112 小时前
使用 Python 加密、保护和签名 PowerPoint 演示文稿 (PPT)
python·powerpoint·加密 ppt·保护 ppt·给ppt添加数字签名
IT策士2 小时前
第14篇 Docker Compose 开发环境最佳实践:热重载与调试
运维·docker·容器