Reputation: 51
I am trying to copy rows from one CSV to another, and also to remove rows after being copied from the first file.
Please see the code, it is working for only copying specific rows from one CSV file to another, but it is not removing the rows from file 1.
import csv
import os
File1 = 'in.csv'
File2 = 'out.csv'
with open(File1, "r") as r, open(File2, "a") as w:
reader = csv.reader(r, lineterminator = "\n")
writer = csv.writer(w, lineterminator = "\n")
for counter,row in enumerate(reader):
if counter<0: continue
if counter>50:break
writer.writerow(row)
with open(File1, "w") as r:
reader = csv.writer(r, lineterminator = "\n")
for counter,row in enumerate(reader):
if counter<0: continue
if counter>50:break
reader.writerow(row)
Please let me know how this would work after coping the rows to the File 2 and then remove those rows from File 1.
Here is the error:
for counter,row in enumerate(reader):
TypeError: '_csv.writer' object is not iterable
Upvotes: 2
Views: 17459
Reputation: 46759
You appear to be trying to move the first 50 rows from one file and append them to another. This needs to be done in a few steps:
Read each of the 50 rows from in.csv
and append each one to out.csv
.
Write the remaining rows from in.csv
to a temporary file.
Delete the original in.csv
file and rename the temporary file to be in.csv
.
For example:
import itertools
import csv
import os
file_in = 'in.csv'
file_out = 'out.csv'
file_temp = '_temp.csv'
with open(file_in, "r", newline='') as f_input, \
open(file_out, "a", newline='') as f_output, \
open(file_temp, "w", newline='') as f_temp:
csv_input = csv.reader(f_input)
# Append first 50 rows to file_out
csv.writer(f_output).writerows(itertools.islice(csv_input, 0, 50))
# Write the remaining rows from file_in to file_temp
csv.writer(f_temp).writerows(csv_input)
# Rename f_temp to file_in, first remove existing file_in then rename temp file
os.remove(file_in)
os.rename(file_temp, file_in)
This assumes you have a standard comma delimited file and that you are using Python 3.x.
Upvotes: 2