方式一:使用file
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
#!/usr/bin/python
poem='abc\n'
f=file('poem.txt','w')
f.write(poem)
f.close()
注意:file()的第二個參數,“w”表示以“寫”的方式打開檔案
方式二:使用open
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
>>> a=['a\n','111\n','yyy\n']
>>> a
['a\n', '111\n', 'yyy\n']
>>> f=open('c.txt','w')
>>> f.writelines(a)
>>> f.close
注意:open()的第二個參數,“w”表示以“寫”的方式打開檔案
方式三:(僅适用于python3)
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL3gjN5gzN3gjMxcHavw1LcpDc0RHaiojIsJye.png)
>>> man_file=open('man_data.txt','w')
>>> print(['abc','\n'],file=man_file)
>>> man_file.close()
>>>
root@ function_study# ls
man_data.txt nest.py
root@ function_study# cat man_data.txt
['abc', '\n']