使用 python 中的 csv 模块写入特定单元格
我必须向 csv 文件中的特定单元格(例如第 8 个单元格)写入一个值。 我可以看到有一个 csvwriter.writerow(row) 方法可以写入整行,但我没有看到任何可以将值写入特定单元格的内容。
I have to write a value to a particular cell (say the 8th cell) in my csv file.
I can see there is a csvwriter.writerow(row)
method to write an entire row, but I am not seeing anything to write a value to a particular cell.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
csv 模块 提供了读取和写入 csv 文件的功能,但是不允许就地修改特定单元格。
即使您在问题中突出显示的 csvwriter.writerow(row) 方法也不允许您识别和覆盖特定行。相反,它将
row
参数写入写入器的文件对象,实际上它只是在与写入器关联的 csv 文件中追加一行。不过,不要阻止使用 csv 模块,它使用起来很简单,并且通过提供的原语,您可以相对轻松地实现您正在寻找的更高级别的功能。
例如,看一下以下 csv 文件:
单词
four
位于第 3 列(第四列,但行只是一个列表,因此索引是从零开始的),可以轻松更新为使用以下程序包含数字4
:结果输出:
创建一些允许识别和更新特定行和列的通用函数需要更多工作,但与操作Python 中的 .csv 文件只是操作一系列列表。
The csv module provides facilities to read and write csv files but does not allow the modification specific cells in-place.
Even the
csvwriter.writerow(row)
method you highlight in your question does not allow you to identify and overwrite a specific row. Rather it writes therow
parameter to the writer’s file object, in effect it simply appends a row the csv file associated with the writer.Do not be dissuaded from using the csv module though, it is simple to use and with the primitives provided you could implement the higher level functionality you are looking for relatively easily.
For example take a look at the following csv file:
The word
four
is in column 3 (the fourth column but a row is just a list so the indexing is zero based), this can be easily updated to contain the digit4
with the following program:Resulting in the output:
Granted creating some generic function that allows specific rows and columns to be identified and updated is a little more work, but not much more as manipulating a csv file in Python is just manipulating a sequence of lists.
假设您有一个名为 mylist.csv 的 csv 文件,其中包含以下几行:
如果您想将 'h' 修改为 'X',可以使用此代码,需要导入 csv 模块:
如果您想修改每一行的特定列,只需添加for循环即可进行迭代。
suppose you have a csv file called mylist.csv with following lines:
if you want to modify 'h' to become 'X', can use this code, need to import csv module:
If you want to modify a particular column for each row, just add the for loop to iterate.
我同意,这很烦人。我最终将 csv.DictReader 子类化。这允许就地进行基于单元格的查找编辑和转储。我在 activestate 上发布了代码: 就地 csv 查找、操作和导出
I agree, this is annoying. I wound up subclassing csv.DictReader. This allows for cell based lookup edit in place, and dump. I have the code posted on activestate: In place csv lookup, manipulation and export
使用 xlwt 模块,可以在电子表格上执行多种操作。可以写入 Excel 中的特定或特定单元格。
Using xlwt module, one can perform multiple operations on spreadsheet.can write into particular or specific cell in Excel.
如果您确实需要在 .csv 文件中写入特定单元格并且无法避免使用此模块,则可以通过硬编码方法来实现。
假设您想要单元格 H3 中的某些内容:
If you really need to write a specific cell in a .csv file and you can't avoid using this module, there is a hard coding way to do it.
Let's say you want something in the cell H3: