1. 程式人生 > 程式設計 >python學習將資料寫入檔案並儲存方法

python學習將資料寫入檔案並儲存方法

python將檔案寫入檔案並儲存的方法:

使用python內建的open()函式將檔案開啟,用write()函式將資料寫入檔案,最後使用close()函式關閉並儲存檔案,這樣就可以將資料寫入檔案並儲存了。

示例程式碼如下:

file = open("ax.txt",'w')
file.write('hskhfkdsnfdcbdkjs')
file.close()

執行結果:

python學習將資料寫入檔案並儲存方法

內容擴充套件:

python將字典中的資料儲存到檔案中

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('fruit\t place\t digital\t number\n')
	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()

到此這篇關於python學習將資料寫入檔案並儲存方法的文章就介紹到這了,更多相關python將資料寫入檔案並儲存詳解內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!