-1

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)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
AAAAAAbc
  • 19
  • 6
  • What is the issue with the code? Did you get an error or did the code give unexpected results? – tax evader Oct 16 '21 at 04:18
  • And? What is your issue/question? – mozway Oct 16 '21 at 04:20
  • @taxevader Both of these code are not working, when I use a csv file to test them, nothing changed.... – AAAAAAbc Oct 16 '21 at 04:24
  • @mozway My code is not working, it doesn't delete or replace anything from the file, I don't know why... – AAAAAAbc Oct 16 '21 at 04:25
  • You may want to read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). In particular, use an IDE and debug the code, or add print statements instead of file-writing – OneCricketeer Oct 16 '21 at 04:25

1 Answers1

0
  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; e.g. 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(',')

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    I *guess* the delete code should have a `if keyword in line` test, not a full line match. (But I shouldn't have to guess and OP should make the expected behavior and current issue explicit) – mozway Oct 16 '21 at 04:24