要在 Python 中写入 CSV,请使用 Python 的 csv 模块。
例如,让我们将一个字符串列表写入一个新的 CSV 文件:
import csv data = ["This", "is", "a", "Test"] with open('example.csv', 'w') as file: writer = csv.writer(file) writer.writerow(data)
因此,您会在当前文件夹中看到一个名为 example.csv 的文件。
用 Python 编写 CSV 的 4 个步骤
要在 Python 中写入 CSV 文件:
1. 以写入模式打开 CSV 文件。 这是使用 open() 函数发生的。 给它文件的路径作为第一个参数。 将模式指定为第二个参数(“r”表示读取,“w”表示写入)。
2. 创建 CSV 编写器对象。 为此,创建一个 csv 模块的 writer() 对象,并将打开的文件作为其参数传递。
3. 将数据写入 CSV 文件。 使用 writer 对象的 writerow() 函数将数据写入 CSV 文件。
4. 关闭 CSV 文件,使用文件的 close() 方法。
这是一个说明此过程的示例:
import csv # 1. file = open('test.csv', 'w') # 2. writer = csv.writer(file) # 3. data = ["This", "is", "a", "Test"] writer.writerow(data) # 4. file.close()
这段代码在当前文件夹中创建了一个名为 test.csv 的文件。
如果指定的文件不存在,open() 函数将打开一个新文件。 如果是,则打开现有文件。
速写
要缩短写入 CSV 的时间,请使用 with 语句打开文件。 这样你就不用担心自己关闭文件了。 with 会自动处理该部分。
例如:
import csv # 1. step with open('test.csv', 'w') as file: # 2. step writer = csv.writer(file) # 3. step data = ["This", "is", "a", "Test"] writer.writerow(data)
这将在当前文件夹中创建一个名为 test.csv 的新 CSV 文件,并将字符串列表写入其中。
如何在 Python 中将非 ASCII 字符写入 CSV
默认情况下,您不能将非 ASCII 字符写入 CSV 文件。
要支持将非 ASCII 值写入 CSV 文件,请在 open() 调用中将字符编码指定为第三个参数。
with open('PATH_TO_FILE.csv', 'w', encoding="UTF8")
其余过程遵循您之前学到的步骤。
如何为 CSV 文件创建标题
到目前为止,您已经创建了缺少结构的 CSV 文件。
在 Python 中,可以使用用于将任何数据写入 CSV
writerow() 函数为任何 CSV 文件编写标头。
例子: 让我们创建一个包含学生数据的示例 CSV 文件。
为了有效地建立数据,需要在CSV文件的开头为学生创建一个标题并将其插入。您可以按照之前相同的步骤将数据写入CSV文件,这样就可以完成操作。
这是代码:
import csv # Define the structure of the data student_header = ['name', 'age', 'major', 'minor'] # Define the actual data student_data = ['Jack', 23, 'Physics', 'Chemistry'] # 1. Open a new CSV file with open('students.csv', 'w') as file: # 2. Create a CSV writer writer = csv.writer(file) # 3. Write data to the file writer.writerow(student_header) writer.writerow(student_data)
这会将 students.csv 文件创建到您当前正在使用的文件夹中。新文件如下所示:
如何在 Python 中将多行写入 CSV 文件
在 Python 中,您可以使用 CSV 编写器的 writerows() 函数同时将多行写入 CSV 文件。
例子。 假设您要将多行数据写入 CSV 文件。 例如,您可能有一个学生列表,而不是只有其中一个。
要将多行数据写入 CSV,请使用 writerows() 方法。
这是一个例子:
import csv student_header = ['name', 'age', 'major', 'minor'] student_data = [ ['Jack', 23, 'Physics', 'Chemistry'], ['Sophie', 22, 'Physics', 'Computer Science'], ['John', 24, 'Mathematics', 'Physics'], ['Jane', 30, 'Chemistry', 'Physics'] ] with open('students.csv', 'w') as file: writer = csv.writer(file) writer.writerow(student_header) # Use writerows() not writerow() writer.writerows(student_data)
这会生成一个新的 CSV 文件,如下所示:
如何在 Python 中将字典写入 CSV 文件
使用 DictWriter 对象可以实现在 Python 中将字典写入 CSV 文件, 具体包括以下三个步骤:
1. 使用 csv 模块的 DictWriter 对象并在其中指定字段名称。
2. 使用 writeheader() 方法将标头创建到 CSV 文件中。
3. 使用 writerows() 方法将字典数据写入文件。
例子:让我们将学生数据字典写入 CSV 文件。
import csv student_header = ['name', 'age', 'major', 'minor'] student_data = [ {'name': 'Jack', 'age': 23, 'major': 'Physics', 'minor': 'Chemistry'}, {'name': 'Sophie', 'age': 22, 'major': 'Physics', 'minor': 'Computer Science'}, {'name': 'John', 'age': 24, 'major': 'Mathematics', 'minor': 'Physics'}, {'name': 'Jane', 'age': 30, 'major': 'Chemistry', 'minor': 'Physics'} ] with open('students.csv', 'w') as file: # Create a CSV dictionary writer and add the student header as field names writer = csv.DictWriter(file, fieldnames=student_header) # Use writerows() not writerow() writer.writeheader() writer.writerows(student_data)
现在结果与前面示例中的 students.csv 文件相同:
结论
CSV 或逗号分隔值是一种常用的文件格式。 它由通常用逗号分隔的值组成。
要在 Python 中写入 CSV,您需要通过以下步骤使用 csv 模块:
1. 以写入模式打开 CSV 文件。
2. 创建 CSV 编写器对象。
3. 将数据写入 CSV 文件。
4. 关闭 CSV 文件。
这是一个实际的例子。
import csv data = ["This", "is", "a", "Test"] with open('example.csv', 'w') as file: writer = csv.writer(file) writer.writerow(data)
编码愉快!
以上是Python读写csv文件的操作方法的详细内容。更多信息请关注PHP中文网其他相关文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Linux新版
SublimeText3 Linux最新版

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。