Reputation: 2530
Init file looks like this:
1;2019-03-20 22:43:00.934775;200;3;60;0.05;0.05;20_File_18289094.csv;2;
2;2019-03-20 22:46:42.582782;200;3;60;0.05;0.05;21_File_16565692.csv;2;
3;2019-03-20 22:46:52.971144;200;3;60;0.05;0.05;22_File_22368393.csv;
I want to read and remove specific row of same file, my goal is the find first column of a row, and delete it entirely. This is my code so far, but it just replacing ;
to ,
1,2019-03-20 22:43:00.934775,200,3,60,0.05,0.05,20_File_18289094.csv,2,
2,2019-03-20 22:46:42.582782,200,3,60,0.05,0.05,21_File_16565692.csv,2,
3,2019-03-20 22:46:52.971144,200,3,60,0.05,0.05,22_File_22368393.csv,2,
with open(file_master) as inf:
reader = csv.reader(inf.readlines(), delimiter=';')
with open(file_master, 'w') as outf:
writer = csv.writer(outf)
for line in reader:
if str(line[0]) == '1':
writer.writerow(line)
break
else:
writer.writerow(line)
writer.writerows(reader)
Upvotes: 0
Views: 63
Reputation: 421
This does the job.
Open the file with r+
flag which allows read and write.
outdata
is placeholder list for your post "clean up" content.
Loop through lines checking the first value for match with in this case "1"
, otherwise add it to the date that will be written out.
seek
gets you back to the beginning of the file (otherwise you get append like behavior).
Write your cleaned up content.
truncate
gets rid of the previous data that has not yet been written over (otherwise you would get rows 2,3,3).
with open("file_master", 'r+') as outf:
outdata = []
for line in outf.read().split("\n"):
line_items = line.split(";")
if line_items[0] == "1":
pass
else:
outdata.append(",".join(line_items))
outf.seek(0)
outf.write("\n".join(outdata))
outf.truncate()
Upvotes: 1