天天看點

python 寫入檔案

方式一:使用file

python 寫入檔案

#!/usr/bin/python  

poem='abc\n'  

f=file('poem.txt','w')  

f.write(poem)  

f.close()  

 注意:file()的第二個參數,“w”表示以“寫”的方式打開檔案

方式二:使用open

python 寫入檔案

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

python 寫入檔案

>>> 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']