'How to Delete rows with Python
I need a bit of help
This script will delete rows
with open("test1.txt", 'r') as f:
lines = f.readlines()
to_delete = ["apnid","apnzid","apncb"]
new_lines = []
for l in lines:
for d in to_delete:
if d in l:
l = "",
break
new_lines.append(l)
with open("test2.txt", 'w') as file2:
file2.writelines(new_lines)
I'm upgrading it to this
import os
for root, dirs, files in os.walk('Originals\.'):
for name in files:
nmin = os.path.join(root,name)
with open(nmin,"r") as f:
lines = f.readlines()
to_delete = ["apnid","apnzid","apncb"]
new_lines = []
for l in lines:
for d in to_delete:
if d in l:
l = ""
break
new_lines.append(l)
with open(nmin,"w") as fout:
fout.writelines(new_lines)
I run the Run Module and I get no error
Could you help me find where the problem
The script opens the CMD window and closes right away it doesn't delete any rows
Before
"apnid": -2147483648,
"apnzid": -2147483648,
"apncf": -2147483648,
"apncb": -2147483648,
"apfid": -2147483648,
Results
"apncf": -2147483648,
"apfid": -2147483648,
Solution 1:[1]
This will actually REMOVE the lines, rather than replace then with blanks:
import os
to_delete = ["apnid","apnzid","apncb"]
for root, dirs, files in os.walk('Originals\.'):
for name in files:
nmin = os.path.join(root,name)
with open(nmin,"r") as f:
lines = f.readlines()
new_lines = []
for l in lines:
for d in to_delete:
if d in l:
break
else:
new_lines.append(l)
with open(nmin,"w") as fout:
fout.writelines(new_lines)
Note that there is no particular reason to build the new_lines list. You could just be doing the write inside the loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
