0

如何使“file.write(repr(fieldNames1))”将我输入的内容写入“fieldNames1”?

import easygui

#Multi Enter Box
fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXAMPLE: Mad & Stressed)','Behavior:(EXAMPLE: Arguing with family)']

#Write to file
file = open('Fieldnames test.txt', 'a')
file.write(repr(fieldNames1))
file.close()

无论我在“fieldnNames1”中输入什么,都使用以下文本创建一个名为“Fieldnames test.txt”的文件。

['情况:(示例:等待迟到的朋友。)','想法:(示例:我的朋友鲍勃总是迟到!)','情绪:(示例:疯狂和压力)','行为:(示例:与家人争吵)']

4

1 回答 1

2

问题是调用repr()列表会从列表中创建一个字符串。你想要的是这样的:

f = open('output.txt', 'a')
f.write('\n'.join(fieldNames1))
f.close()

write()方法不会自动创建换行符,因此您可以join()使用适合您平台的换行符(例如\n)将字符串列表放在一起。您可以在Python 文档中阅读有关文件对象的更多信息。

另外,我建议使用与 不同的变量file,因为file它实际上是一个 Python 函数。该代码将起作用,但您应该注意可能出现的意外情况。

于 2011-11-04T06:34:02.650 回答