0

我正在尝试将字符串列表写入 Python 中的文件。这样做时我遇到的问题是输出的外观。我想在没有列表结构的情况下编写列表的内容。

这是将列表写入文件的代码部分:

loglengd = len(li)
runs = 0
while loglengd > runs:
    listitem = li[runs]
    makestring = str(listitem)
    print (makestring)
    logfile.write(makestring + "\n")
    runs = runs +1
print("done deleting the object")
logfile.close()

这给我的输出如下所示:

['id:1\n']
['3\n']
['-3.0\n']
['4.0\n']
['-1.0\n']
['id:2\n']
['3\n']
['-4.0\n']
['3.0\n']
['-1.0\n']
['id:4\n']
['2\n']
['-6.0\n']
['1.0\n']
['-1.0\n']

这就是它应该看起来的样子:

id:1
3
-3.0
4.0
-1.0
id:2
3
-4.0
3.0
-1.0
id:4
2
-6.0
1.0
-1.0
4

3 回答 3

2
  1. 请学习如何使用循环(http://wiki.python.org/moin/ForLoop

  2. li似乎是列表列表,而不是字符串列表。因此,您必须使用listitem[0]来获取字符串。

如果您只想将文本写入文件:

text='\n'.join(listitem[0] for listitem in li)
logfile.write(text)
logfile.close()

如果您还想在循环中执行某些操作:

for listitem in li:
    logfile.write(listitem[0] + '\n')
    print listitem[0]
logfile.close()
于 2012-06-14T18:53:49.893 回答
0
for s in (str(item[0]) for item in li):
    print(s)
    logfile.write(s+'\n')

print("done deleting the object")
logfile.close()
于 2012-06-15T02:31:39.233 回答
-2

您正在搜索的字符串函数是 strip()。

它是这样工作的:

logs = ['id:1\n']
text = logs[0]
text.strip()
print(text)

所以我认为你需要这样写:

loglengd = len(li)
runs = 0
while loglengd > runs:
    listitem = li[runs]
    makestring = str(listitem)
    print (makestring.strip())     #notice this
    logfile.write(makestring + "\n")
    runs = runs +1
print("done deleting the object")
logfile.close()
于 2012-06-14T18:56:19.660 回答