简体   繁体   中英

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

  2. li seems to be a list of lists, instead of a list of strings. Therefore you must use listitem[0] to get the string.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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