2014-03-02 2 views
0

내 CSV의 첫 번째 열을 읽으려고합니다.이 열을 사용하여 웹 서비스를 실행하고이 출력을 가져 와서 내 CSV에 추가하려고합니다. 저는 이것을 줄 단위로하고 싶습니다. 여기즉시 CSV에 열을 추가하는 방법

내가 지금까지 함께 온 것입니다 :

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter='\n') 
with open('FinalCSV.csv','rb') as tsvin, open('FinalCSV.csv', 'a+b') as csvout: 
    tsvin = list(np.array(p.read_table('train.tsv'))[:,0]) 
    writer = csv.writer(csvout) 
    count = 0 
    for row in csvout: 
     sep = '|' 
     row = row.split(sep, 1)[0] 
     cmd = subprocess.Popen("python GetJustAlexaRanking.py " + row , 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE, 
          shell=True) 
     (output, err) = cmd.communicate() 
     exit_code = cmd.wait() 
     outlist = output.split('\r\n') 
     try: 
      outrank1 = outlist[1][outlist[1].index(':')+1:] 
     except ValueError: 
      outrank1 = "?" 
     row.append(str(outrank1).rstrip()) #writing,error here 
     print [str(outlist[0]).rstrip(), str(outrank1).rstrip()] 
     count+=1 

그러나이 나에게

Traceback (most recent call last): 
    File "File.py", line 28, in <module> 
    row.append(str(outrank1).rstrip()) #writing,error here 
AttributeError: 'str' object has no attribute 'append' 

가 어떻게 내가 원하는 것을 달성 할 수있는 오류를주고있다?

편집 :

loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter='\n') 
with open('FinalCSV.csv','rb') as tsvread, open('FinalCSVFin.csv', 'wb') as csvout: 
    tsvin = list(np.array(p.read_table('train.tsv'))[:,0]) 
    writer = csv.writer(csvout) 
    count = 0 
    for row in tsvread: 
     sep = '|' 
     row = row.split(sep, 1)[0] 
     cmd = subprocess.Popen("python GetJustAlexaRanking.py " + row , 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE, 
          shell=True) 
     (output, err) = cmd.communicate() 
     exit_code = cmd.wait() 
     outlist = output.split('\r\n') 
     try: 
      outrank1 = outlist[1][outlist[1].index(':')+1:] 
     except ValueError: 
      outrank1 = "?" 
     row = [row, outrank1.rstrip()] 
     writer.writerow(row) 
     print [str(outlist[0]).rstrip(), str(outrank1).rstrip()] 
     count+=1 

답변

1

귀하의 row은 목록이 아니라 문자열 :

row = row.split(sep, 1)[0] 

그런 다음 subprocess 명령에 해당 문자열을 사용합니다.

다시 목록으로 만들어야합니다. 대신 append의 사용 : outrank1 어쨌든 항상 문자열입니다

row = [row, outrank1.rstrip()] 

이 필요 그것에 str() 전화가 없습니다.

csvout 파일 핸들에서 읽고 쓰려고 할 때 읽기/쓰기 위치에 대해 매우주의해야합니다. 파일 핸들에 쓸 수 없으며 예를 들어 기존 데이터를 바꿀 수 있습니다. 쓰고 새 파일을 별도로 사용하는 것이 가장 좋습니다. 기존 파일 위치를 바꿔 가며 바꿉니다.

+0

응답 해 주셔서 대단히 감사드립니다. 위의 코드를 편집하여 현재 변경 사항을 실행하고 있는지를 보여줍니다. 이 코드는 이제 실행되지만 출력에 열을 추가하지는 않습니다 (사실 출력 파일에는 아무런 차이가 없습니다). 어떤 제안? 고마워요 :) –

+0

@ SimonKiely : 파일에 행을 쓰지 않고 .. –

+0

죄송합니다, 나는 거기에 잘못된 텍스트를 복사했습니다! 나는 그것을 지금 새롭게했다. 현재 실행 중이지만 결국 IndexError로 인해 실패합니다. 또한 내 출력을 잘못된 형식으로 인쇄합니다 (http://i.imgur.com/borLltB.png). 도와 주셔서 대단히 감사합니다! :) –

관련 문제