简体   繁体   English

如何读取和写入同一个 csv 文件?

[英]How to Read and Write to the Same csv File?

I am trying to read and write to the same csv file, to specifically delete a row in a csv file if a certain header contains a value.我正在尝试读取和写入同一个 csv 文件,如果某个 header 包含一个值,则专门删除 csv 文件中的一行。 My csv file looks like this:我的 csv 文件如下所示:

Item #物品 # Price价格 Quantity数量 Name姓名
1 1 2.99 2.99 1 1 Muffin 1松饼 1
2 2 3.99 3.99 2 2 Muffin 2松饼 2
3 3 4.99 4.99 3 3 Cookie 1饼干 1
4 4 5.99 5.99 4 4 Cookie 2饼干 2

I have the following code:我有以下代码:

def delete_item(self, item_num):
        self.result[:] = [d for d in self.result if d.get("Item #") != int(item_num)]
        input = open('items2.csv', 'rb')
        output = open('items2.csv', 'wb')
        writer = csv.writer(output)
        for row in csv.reader(input):
            if row[0]!=item_num:
                writer.writerow(row)
                input.close()
                output.close()

This method takes in a item_num that is entered by the user, and deletes it from the list of dictionaries I have.此方法接受用户输入的 item_num,并将其从我拥有的字典列表中删除。 I am also trying to get this specific row deleted from my csv file that the data is stored in. For example, if the user inputs they would like to delete the row that has the Item # of 1, it would delete this row in the csv file.我还试图从存储数据的 csv 文件中删除此特定行。例如,如果用户输入他们想要删除项目编号为 1 的行,它会在csv 文件。

I have the following method that I believe does so, but understand I cannot read and write to the same csv file at the same time, as it will simply clear it.我相信以下方法可以做到这一点,但请理解我无法同时读取和写入同一个 csv 文件,因为它只会清除它。 I know this isnt extremely practical, as it can load up memory, but I need to adjust the same csv file, and know this can be done by reading, closing it, and then writing.我知道这不是很实用,因为它可以加载 memory,但我需要调整相同的 csv 文件,并且知道这可以通过读取、关闭然后写入来完成。 How would I do this?我该怎么做?

The same CSV file should look like this after it is done if item_num = 2 .如果item_num = 2 ,相同的 CSV 文件在完成后应该如下所示。

Item #物品 # Price价格 Quantity数量 Name姓名
1 1 2.99 2.99 1 1 Muffin 1松饼 1
3 3 4.99 4.99 3 3 Cookie 1饼干 1
4 4 5.99 5.99 4 4 Cookie 2饼干 2

As you said, you can't (or really shouldn't try to ) concurrently read and write the same file.正如你所说,你不能(或者真的不应该尝试)同时读写同一个文件。 There are several options.有几种选择。

  1. If you don't care about preserving the old file:如果您不关心保留旧文件:
  • read the whole file in to a dictionary.将整个文件读入字典。
  • close the file that is read关闭读取的文件
  • monkey with the dictionary as needed根据需要使用字典进行猴子
  • open and write the same file with the 'w' modifier on the write command to over-write the current contents在写入命令上使用“w”修饰符打开并写入相同的文件以覆盖当前内容
  1. If you want to save the orig file (usually a great idea):如果要保存原始文件(通常是个好主意):
  • read the whole file into a dictionary将整个文件读入字典
  • close the file, perhaps rename it to <filename>_orig关闭文件,也许将其重命名为<filename>_orig
  • monkey with the dictionary有字典的猴子
  • open a new file with the old name (or in a new folder of mods )用旧名称打开一个新文件(或在mods的新文件夹中)
  1. If you are doing this a lot, it starts to smell like a database so:如果你经常这样做,它开始闻起来像一个数据库,所以:
  • make the jump to sqlite, which is included in core python跳转到 sqlite,它包含在核心 python 中
  • read/write concurrently to your heart's content.随心所欲地同时读/写。

TL;DR Summary: do the reading / writing operations sequentially TL;DR 摘要:按顺序执行读/写操作

You're not doing it concurrently like the other user suggests.您不会像其他用户建议的那样同时执行此操作。 You're working with it sequentially, row by row, byte by byte.您正在按顺序、逐行、逐字节地使用它。 It's completely safe.这是完全安全的。 You may even use only a single descriptor doing it.您甚至可以只使用一个描述符来执行此操作。 That should do it应该这样做

def delete_item(self, item_num):
        self.result[:] = [d for d in self.result if d.get("Item #") != int(item_num)]
        editing = open('items2.csv', 'r+b')
        pointer = 0
        for row in csv.reader(editing):
            if row[0] == item_num:
                rest = editing.read()
                editing.seek(pointer)
                editing.write(rest)
                editing.truncate()
                editing.close()
                break
            pointer = editing.tell()

This code assumes there's only one row with the provided item #此代码假定提供的项目只有一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM