python學習將數(shù)據(jù)寫入文件并保存方法
python將文件寫入文件并保存的方法:
使用python內(nèi)置的open()函數(shù)將文件打開,用write()函數(shù)將數(shù)據(jù)寫入文件,最后使用close()函數(shù)關(guān)閉并保存文件,這樣就可以將數(shù)據(jù)寫入文件并保存了。
示例代碼如下:
file = open('ax.txt', ’w’)file.write(’hskhfkdsnfdcbdkjs’)file.close()
執(zhí)行結(jié)果:
內(nèi)容擴展:
python將字典中的數(shù)據(jù)保存到文件中
d = {’a’:’aaa’,’b’:’bbb’}s = str(d)f = open(’dict.txt’,’w’)f.writelines(s)f.close()
實例2:
def main():list1 = [[’西瓜’,’蘭州’,’first’,20],[’香蕉’,’西安’,’second’,30],[’蘋果’,’銀川’,’third’,40],[’桔子’,’四川’,’fourth’,40]]output = open(’data.xls’,’w’,encoding=’gbk’)output.write(’fruitt placet digitalt numbern’)for i in range(len(list1)):for j in range(len(list1[i])):output.write(str(list1[i][j])+’ ’)output.write(’t’)output.write(’n’)output.close() if __name__ == ’__main__’:main()
到此這篇關(guān)于python學習將數(shù)據(jù)寫入文件并保存方法的文章就介紹到這了,更多相關(guān)python將數(shù)據(jù)寫入文件并保存詳解內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
