简体   繁体   中英

How to delete or replace specific line of csv file

I want to delete and replace function on a CSV file only by using os and sys module (version is python 3).

I've tried this for replace function:

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)

and this for delete function:

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. Strings are immutable.

    • You cannot call .replace() and expect the variable to change
    • Assigning a variable to a replace() method call doesn't update the file on-disk; eg you need to call f.write(line.replace(...))
  2. open(file, 'w') is clearing the file content. Your replace code therefore leaves behind an empty file.

  3. Your delete code seems okay assuming your lines exactly match your keyword, as it is a copy of this post , but if you are running it multiple times, then you keep modifying the same file, so nothing should happen on the next run(s) as all keywords would be gone.

    If you want to delete based on columns of the CSV, then you should split the line on your CSV delimter, and use something like if keyword not in line.split(',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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