2013-05-16 3 views
1

나는이 OUTFILE에 목록과 밖으로 인쇄 걸립니다이 기능 : 모든 튜플 후인쇄 출력

def writeToFile(files): 

for path2 in files: 
    fi= open(fileo, 'w') 
    fi.truncate() 
    fi.write('\n' + str(foundFiles2)) 
    fi.close() 


foundFiles2 = [ 
'bb.TechnicalDefinition.UnitTests.vbproj' 
'bb.Units.UnitTests.vbproj' 
'bb.Utilities.UnitTests.vbproj' 
'bb.Visualization.UnitTests.vbproj' ] 

그것은 파일에 문제를 인쇄합니다 그러나 나는 그것이 새로운 라인을 인쇄 할 명부. 이 파일에 쓸 때, 그것은 다음과 같습니다

'bb.APDS.UnitTests.vbproj', 'bb.DatabaseAPI.UnitTests.vbproj', 'bb.DataManagement.UnitTests.vbproj', 

은 내가

fi.write('\n' + str(foundFiles2)) 

새로운 라인에 별도로 각 튜플을 인쇄 할 것이라고 생각하지만 그렇지 않습니다. 여기에 어딘가에 루프가 필요합니까, 아니면 구문이 틀린가요?

답변

1

str 버전을 인쇄하는 대신 목록을 반복해야합니다.

>>> lis = [1,2,3] 
>>> str(lis)  #str just returns a string representation of the string 
'[1, 2, 3]' 
>>> for x in lis : #use for loop to iterate over individual items of the list 
...  print x 
...  
1 
2 
3 

코드 :

for path2 in files: 
    #"w" mode automatically truncates the file for you 
    # Always use `with` statement for handling files, it automatically 
    # closes the file.  
    with open(fileo,"w") as f:  
     for text in foundFiles2: #iterate over each value in the list 
      f.write(text+"\n") 
+0

당신은 정말 대단합니다, 정말 고마워요! 완벽하게 작동합니다. – bbesase

+0

@bbasease 기꺼이 도와주었습니다. :) –

1

열고 for 루프 전에 파일 및 루프에 대한 후 파일을 닫습니다 (.하거나 자동으로 작업을 수행하기 때문에 애쉬 위니 제안처럼 with 사용)

당신이가는 길에, 얼마나 많은 인덱스가 files에 있는지에 따라 동일한 foundFiles2리스트를 반복해서 쓰게됩니다.

for item in foundFiles2: 
    fi.write(item+'\n') 

이가 첫 번째 항목으로 이동 한 다음 쓰기를 한 후 두 번째 항목됩니다 foundFiles2 만약

당신이 for 문에서 사용할 필요는 다음 반복 할 목록입니다 그런 다음 등을 써라.