[Network security takes you to practice reptiles-100 exercises] Practice 13: File creation and writing

Table of contents

Goal: write data to a file

 Network Security O


Goal: write data to a file

open

(Starting from the value of appearance) Open one, if there is no one, it will be created

with open('data.csv', mode='w', newline='') as file:

(loyal to talent) start writing data

    writer = csv.writer(file)
    writer.writerows(data)


 full code

import csv

# 数据
data = [
    ['姓名', '年龄', '性别'],
    ['张三', 25, '男'],
    ['李四', 30, '男'],
    ['王五', 28, '女']
]

# 创建并写入 CSV 文件
with open('data.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    for row in data:
        writer.writerow(row)

print("CSV 文件创建并写入成功!")


 Equivalent logic:

    for row in data:
        writer.writerow(row)
    writer.writerows(data)


 Notes:

1、with open('data.csv', mode='w', newline='') as file
使用open()函数打开名为data.csv的文件,并以写入模式(mode='w')打开
newline=''参数用于避免在写入CSV文件时出现额外的空行
使用with语句可以确保文件在使用完毕后会被正确关闭。

2、writer = csv.writer(file)
创建一个csv.writer对象,用于写入CSV文件。传入文件对象file作为参数。

3、for row in data
遍历data列表中的每一行数据。

4、writer.writerow(row)
使用writer对象的writerow()方法将每一行数据写入CSV文件中
每次调用writerow()都会将一行数据写入文件,并在每个数据之间自动添加逗号


 Note 1:

Whether the data has multiple rows

writer.writerows()方法用于写入多行数据(可迭代对象)
writer.writerow()写入单个的数据值


 scene one:

Write the data in the list at one time

(so that it can be used directly)

writer.writerows()


 Scene two:

If it is a for loop, write line by line

(that is, it will wrap)

mode='w' 改为 mode='a


operation result



 Network Security O

README.md Book Bansheng/Network Security Knowledge System-Practice Center-Code Cloud-Open Source China (gitee.com) https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md

GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge

Guess you like

Origin blog.csdn.net/qq_53079406/article/details/131738410