gpt4 book ai didi

python - 打印输出格式

转载 作者:行者123 更新时间:2023-12-01 05:44:26 25 4
gpt4 key购买 nike

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

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

会在新行上单独打印每个元组,但事实并非如此。我是否需要在此处某个地方循环,或者我的语法完全错误?

最佳答案

您应该迭代列表而不是打印它的 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")

关于python - 打印输出格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16594314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com