You have to open the first file as "r+" in order to read and write, like so:
f = open(filename,"r+")
for line in f:
e = line.split(',')
if len(e) > 28:
with open(filename2, "a") as text_file:
text_file.write(line.encode('cp1252'))
f.seek(0)
f.truncate()
f.close()
I have also made the code more efficient as it should iterate over the lines instead of copying them to the side. An even more efficient approach would be this:
with open(filename,"r+") as file1, open(filename2, "a") as file2:
for line in f:
if line.count(',') > 27:
file2.write(line.encode('cp1252'))
file1.truncate(0)
That way you don't reopen the file every iteration, and since you're not using the split values, you can just count the commas (,) and compare to 27 instead of 28.
Removing only the copied lines
If you wish to remove only the copied lines and not empty the file, you have no way other than copying the entire file to the memory or using a tempfile.
That's the way to do it by copying to memory:
with open(filename,"r+") as file1, open(filename2, "a") as file2:
file_lines = file1.readlines()
file1.seek(0)
file1.truncate()
for line in file_lines:
if line.count(',') > 27:
file2.write(line.encode('cp1252'))
else:
file1.write(line)
Please make sure to specify an encoding if you're using Python 3.X.