簡體   English   中英

如何刪除或替換csv文件的特定行

[英]How to delete or replace specific line of csv file

我只想通過使用 os 和 sys 模塊(版本為 python 3)來刪除和替換 CSV 文件上的函數。

我試過這個替換功能:

file = "test.csv"

keyword = "blah"

old = "the old word"
new = "the new word"


with open(file, "r") as f:
    lines = f.readlines()
with open(file, "w") as f:
    for line in lines:
        if keyword in line:
            line.replace(old, new)

這用於刪除功能:

file = "test.csv"

keyword = "blahblah"

with open(file, "r") as f:
    lines = f.readlines()
with open(file, "w") as f:
    for line in lines:
        if line.strip("\n") != keyword:
            f.write(line)
  1. 字符串是不可變的。

    • 你不能調用.replace()並期望變量改變
    • 將變量分配給replace()方法調用不會更新磁盤上的文件; 例如你需要調用f.write(line.replace(...))
  2. open(file, 'w')正在清除文件內容。 因此,您的替換代碼會留下一個空文件。

  3. 假設您的行您的關鍵字完全匹配,您的刪除代碼似乎沒問題,因為它是這篇文章的副本,但是如果您多次運行它,那么您會不斷修改同一個文件,因此下次運行時不會發生任何事情因為所有關鍵字都將消失。

    如果您想根據 CSV 的列刪除,那么您應該在 CSV if keyword not in line.split(',')上拆分該行,並使用類似if keyword not in line.split(',')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM