위치를 편집하여 CSV 파일에 행을 추가하려면 어떻게해야합니까? 나는 원래, (의사)을 임시 파일에 기록한 다음, 교체의 패턴을 피하려는 : 중간 복사본을 만들지 않고 csvfile에 행 추가
add_records_to_csv(newdata, infile, tmpfile)
delete(infile)
rename(tmpfile, infile)
는 여기에 실제 기능입니다. 기존의이 기록으로 새로운 행이 동일한 구조를 가지고 있다면
이
def add_records_to_csv(dic, csvfile):
""" Append a dictionary to a CSV file.
Adapted from http://pymotw.com/2/csv/
"""
f_old = open(csvfile, 'rb') # <--
csv_old = csv.DictReader(f_old) # <--
fpath, fname = os.path.split(csvfile) # <--
csvfile_new = os.path.join(fpath, 'new_' + fname) # <--
print(csvfile_new) # <--
f = open(csvfile_new, 'wb') # <--
try:
fieldnames = sorted(set(dic.keys() + csv_old.fieldnames))
writer = csv.DictWriter(f, fieldnames=fieldnames)
headers = dict((n,n) for n in fieldnames)
writer.writerow(headers)
for row in csv_old:
writer.writerow(row)
writer.writerow(dic)
finally:
f_old.close()
f.close()
return csvfile_new
파일 (바이트)의 크기는 어느 정도입니까? 몇 줄의 원본과 예상 된 결과를 게시 할 수 있습니까? – wwii
@wwii, [여기] (https://github.com/maphew/Speed-test/tree/master/stats/GEOMATT)는 csv의 일부입니다. 완전히 대표적인 세트는 아니지만 다른 열이있는 것들이 있습니다. Dan이 덕분에 개별적으로 처리해야한다는 것을 깨달았습니다. –