2017-12-11 24 views
0

저는 Python을 처음 사용합니다. CSV 파일에 숫자를 쓰려고합니다. 첫 번째 숫자는 행의 첫 번째 요소를 만듭니다. 두 번째 숫자가 두 번째로 나오면 새 행이 시작됩니다. 그러나 두 번째 요소를 같은 행에 추가하는 대신 내 코드가 작동하는 방식으로 새 행이 만들어집니다. 예를 들어CSV 기록기가 각 입력 값에 대해 다음 행으로 이동합니다.

는 내가 원하는 것은 :

a1,b1 
a2,b2 

하지만 내가 얻을 것은 :

n = Ratio # calculated in each loop 
with open('ex1.csv', 'ab') as f: 
    writer = csv.writer(f) 
    writer.writerow([n]) 
    ... 

m = Ratio2 # calculated in each loop 
with open('ex1.csv', 'ab') as f: 
    writer = csv.writer(f) 
    writer.writerow([m]) 
:

a1 
b1 
a2 
b2 

내가 지속적으로 CSV 파일에 값을 기록하는 루프를 사용하여

결과가

형식으로 표시되도록하고 싶습니다.
n1,m1 
n2,m2 
+1

그리고'함께 n'과'm', 즉'writer.writerow ([N, m은])' – zwer

+0

당신은 ','로 구분 기호를 지정해야 할 수 있습니다 – johnashu

+0

가입 [Clomplete minimal example] (https://stackoverflow.com/help/mcve)은 문제를보다 쉽게 ​​재현하는 데 도움이됩니다. – Nogoseke

답변

1

파일에 쓰기 위해 예 다음 다시 읽고 그것을 인쇄 :

import csv 

with open('ex1.csv', 'w') as f: # open file BEFORE you loop 
    writer = csv.writer(f)  # declare your writer on the file 

    for rows in range(0,4):  # do one loop per row 
     myRow = []    # remember all column values, clear list here 
     for colVal in range(0,10): # compute 10 columns 
      m = colVal * rows  # heavy computing (your m or n) 
      myRow.append(m)   # store column in row-list 

     writer.writerow(myRow) # write list containing all columns 

with open('ex1.csv', 'r') as r: #read it back in 
    print(r.readlines())   # and print it 

출력 :

0,0,0,0,0,0,0,0,0,0 
0,1,2,3,4,5,6,7,8,9 
0,2,4,6,8,10,12,14,16,18 
0,3,6,9,12,15,18,21,24,27 

의 파일로 변환

['0,0,0,0,0,0,0,0,0,0\r\n', '0,1,2,3,4,5,6,7,8,9\r\n', '0,2,4,6,8,10,12,14,16,18\r\n', '0,3,6,9,12,15,18,21,24,27\r\n'] 

당신 또한 각 행 목록을 채우고 (myList[:]로 복사) 다른 목록에 넣고 writer.writerows([ [1,2,3,4],[4,5,6,7] ])을 wr로 사용합니다. 한 줄에 모든 행을 표시합니다.

참조 : https://docs.python.org/2/library/csv.html#writer-objects 또는 https://docs.python.org/3/library/csv.html#writer-objects