简体   繁体   English

如何将Python列表写到文件中?

[英]How do I write a Python list out to a file?

I'm trying to write a list of strings to a file in Python. 我正在尝试将字符串列表写入Python中的文件。 The problem I have when doing this is the look of the output. 执行此操作时遇到的问题是输出的外观。 I want to write the contents of the lists without the list structures. 我想写没有列表结构的列表内容。

This is the part of the code that is writing the list to the file: 这是将列表写入文件的代码部分:

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

The output this is giving me looks like this: 这给我的输出看起来像这样:

['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']

and this is what it is supposed to look like: 这是应该的样子:

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
  1. Please learn how to use loops ( http://wiki.python.org/moin/ForLoop ) 请学习如何使用循环( http://wiki.python.org/moin/ForLoop

  2. li seems to be a list of lists, instead of a list of strings. li似乎是一个列表列表,而不是字符串列表。 Therefore you must use listitem[0] to get the string. 因此,您必须使用listitem[0]来获取字符串。

If you just want to write the text to a file: 如果只想将文本写入文件:

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

if you also want to do something in the loop: 如果您还想在循环中做点事情:

for listitem in li:
    logfile.write(listitem[0] + '\n')
    print listitem[0]
logfile.close()
for s in (str(item[0]) for item in li):
    print(s)
    logfile.write(s+'\n')

print("done deleting the object")
logfile.close()

The string function you are searching for is strip(). 您要搜索的字符串函数是strip()。

It works like this: 它是这样的:

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

So I think you need to write it like this: 所以我认为您需要这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM