Writing a list to a file with Python

后端 未结 21 1784
孤街浪徒
孤街浪徒 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:06

    Redirecting stdout to a file might also be useful for this purpose:

    from contextlib import redirect_stdout
    with open('test.txt', 'w') as f:
      with redirect_stdout(f):
         for i in range(mylst.size):
            print(mylst[i])
    

提交回复
热议问题