Writing a list to a file with Python

后端 未结 21 1820
孤街浪徒
孤街浪徒 2020-11-22 01:48

Is this the cleanest way to write a list to a file, since writelines() doesn\'t insert newline characters?

file.writelines([\"%s\\n\" % item  fo         


        
相关标签:
21条回答
  • 2020-11-22 02:20

    In Python3 You Can use this loop

    with open('your_file.txt', 'w') as f:
        for item in list:
            f.print("", item)
    
    0 讨论(0)
  • 2020-11-22 02:21
    with open ("test.txt","w")as fp:
       for line in list12:
           fp.write(line+"\n")
    
    0 讨论(0)
  • 2020-11-22 02:21

    In python>3 you can use print and * for argument unpacking:

    with open("fout.txt", "w") as fout:
        print(*my_list, sep="\n", file=fout)
    
    0 讨论(0)
  • 2020-11-22 02:21

    Another way of iterating and adding newline:

    for item in items:
        filewriter.write(f"{item}" + "\n")
    
    0 讨论(0)
  • 2020-11-22 02:21

    Using numpy.savetxt is also an option:

    import numpy as np
    
    np.savetxt('list.txt', list, delimiter="\n", fmt="%s")
    
    0 讨论(0)
  • 2020-11-22 02:24

    You can also use the print function if you're on python3 as follows.

    f = open("myfile.txt","wb")
    print(mylist, file=f)
    
    0 讨论(0)
提交回复
热议问题