简体   繁体   English

就地删除CSV的某些行

[英]Delete some rows of a CSV, in-place

This: 这个:

import csv
with open('original.csv', 'rb') as inp, open('new.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)
os.remove('original.csv')
os.rename('new.csv', 'original.csv')

allows to delete certain rows of a CSV. 允许删除CSV的某些行。

Is there a more pythonic way to delete some rows of a CSV file, in-place? 还有一种更Python的方式就地删除CSV文件的某些行吗? (instead of creating a file, deleting the original, renaming, etc.) (而不是创建文件,删除原始文件,重命名等)

There isn't a more Pythonic way: you can't delete stuff in the middle of a file. 没有更Python化的方法:您不能删除文件中间的内容。 Write out a new file with the stuff you want, and then rename it. 用所需的内容写出一个新文件,然后重命名。

I noticed that your code does not import the os module, even though you're using it. 我注意到即使您正在使用它,您的代码也不会导入os模块。 Regardless, here's a method of doing what you need it to do without using that module. 无论如何,这是一种无需使用该模块即可执行所需操作的方法。

This will open in read mode first to get the data, then write mode to overwrite. 这将首先以读取模式打开以获取数据,然后以写入模式覆盖。 Note that you need to pass the csv.reader(f) statement to the list() function or else the data variable will simply point to the memory address of the CSV file and you won't be able to do anything with the content once it's closed. 请注意,您需要将csv.reader(f)语句传递给list()函数,否则data变量将仅指向CSV文件的内存地址,并且一次将无法对内容执行任何操作它是关闭的。 list() will actually copy the information for you. list()实际上会为您复制信息。

import csv

with open("original.csv", "rb") as f:
    data = list(csv.reader(f))

with open("original.csv", "wb") as f:
    writer = csv.writer(f)
    for row in data:
        if row[2] != "0":
            writer.writerow(row)

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

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