Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - 使用Python将列表写入文件(Writing a list to a file with Python)

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

(这是将列表写入文件的最干净的方法,因为writelines()不会插入换行符吗?)

file.writelines(["%s
" % item  for item in list])

It seems like there would be a standard way...

(似乎会有一种标准的方法...)

  ask by Josh Arenberg translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a loop:

(您可以使用循环:)

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s
" % item)

In Python 2, you can also use

(在Python 2中,您也可以使用)

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

If you're keen on a single function call, at least remove the square brackets [] , so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

(如果您热衷于单个函数调用,请至少删除方括号[] ,以便一次打印一个字符串(一个genexp而不是一个listcomp)-没有理由占用所有实现整个字符串列表所需的内存。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...