1

我有这个函数,它需要一个列表并将其打印到一个输出文件中:

 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))

将在新行上分别打印出每个元组,但事实并非如此。我需要在这里某个地方循环还是我的语法完全错误?

4

2 回答 2

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")   
于 2013-05-16T18:02:03.153 回答
1

在循环之前打开文件for并在 for 循环之后关闭文件(或with像 ashwini 建议的那样使用,因为它会自动执行此操作。)

按照您的处理方式,它只会foundFiles2一遍又一遍地编写相同的列表,具体取决于files.

如果foundFiles2是您要迭代的列表,那么您需要在for语句中使用它:

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

这将转到第一项,然后写它,然后是第二项,然后写它等等。

于 2013-05-16T18:10:28.387 回答