The main reason is deletes all from the file is that you open the same file in read mode and write mode. Opening an existing file in write mode will clear it completely.
Relevant documentation: here
open(filename, mode)
:
The first argument is a string containing the filename
. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r'
when the file will only be read, 'w'
for only writing (an existing file with the same name will be erased), [...]
(emphasis mine)
Your code has plenty of other problems:
input()
stored in input
- overwriting the built in (you edited that, great :o) )
- using binary mode on file open for textfiles
- using the
csv.reader(...)
on a string - not the filehandle
- not using
newline=""
on file open for csv module
- not writing all data to the new file
- comparing the csv
row
(a list) to user_input
which is a string
- trying to open the same file for reading and writing and doing both
- not using context handlers for file operations
To fix it, open a different file for the output, read the input-file, compare the first value of your row to the userinput and skip writing this line if it matches
See other related posts to line deletion in csv at the end - your problem here is not a dupe because those happen to not overwrite the file at hand using the same names.
Create csv demo file:
with open ("color.csv","w") as f:
for color in ['blue', 'crash', 'pink', 'gold', 'silver']:
f.write(f"{color},some other,tabulars in the,csv\n")
Process file:
"""This code deletes rows with a given 'color' in column 0"""
import csv
color_to_delete = "pink" # input("Please enter a row name to be deleted.")
# not binaryy - it is a CSV with is TEXT - and you need to supply newline=""
with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:
writeme = csv.writer(w)
for row in csv.reader(r): # why input? you need the file handle
if row[0] == color_to_delete:
continue # skip this row
writeme.writerow(row)
print("# before:")
print(open("color.csv").read())
print("\n# after:\n" + open("2ndColor.csv").read())
Output:
# before:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
pink,some other,tabulars in the,csv
gold,some other,tabulars in the,csv
silver,some other,tabulars in the,csv
# after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
gold,some other,tabulars in the,csv
silver,some other,tabulars in the,csv
To remove multiple lines after the inputtedcolor you add:
"""This code deletes rows with a given 'color' in column 0 and the following
'lines_to_deete' rows"""
color_to_delete = "pink" # input("Please enter a row name to be deleted.")
lines_to_delete = 1 # will delete the pink line and 1 more
lc = 0
with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:
writeme = csv.writer(w)
for row in csv.reader(r): # why input? you need the file handle
if row[0] == color_to_delete:
lc = lines_to_delete
continue # skip this row
elif lc:
lc -= 1
continue
writeme.writerow(row)
to get an output of:
after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
silver,some other,tabulars in the,csv
To skip certain line ranges, you can do:
import csv
lines_to_skip = range(2,5) # 2,3,4
with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:
writeme = csv.writer(w)
# enumerate the input and skip row if in range
for line_num, row in enumerate(csv.reader(r)): # why input? you need the file handle
if line_num in lines_to_skip:
continue # skip this row
writeme.writerow(row)
to get an output of:
after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
Explanation of the modes for file opening see Difference between modes a, a+, w, w+, and r+ in built-in open function?
Related posts: