1. 程式人生 > >[python]使用txt儲存和讀取列表變數

[python]使用txt儲存和讀取列表變數

問題:

在python實際運用中,我們經常需要將變數儲存在txt檔案中,並且希望未來能讀取他們。這裡我們將自定義兩個函式,來簡化這個操作。

解決:

1.儲存入txt檔案
輸入:content(列表變數),filename(檔名,如'1.txt'),mode(讀寫方式,預設mode = 'a').
輸出:在當前目錄下建立一個名為filename檔案,並且將列表的每個元素逐一寫入檔案(加入換行符).
def text_save(content,filename,mode='a'):
    # Try to save a list variable in txt file.
    file = open(filename,mode)
    for
i in range(len(content)): file.write(str(content[i])+'\n') file.close()
2.讀取出txt檔案
輸入:filename(檔名,如'1.txt').
輸出:函式返回一個列表,裡面包含每行的內容,並且自動遮蔽換行符(如果沒有找到該檔名,返回空列表).
def text_read(filename):
    # Try to read a txt file and return a list.Return [] if there was a mistake.
    try:
        file = open(filename,'r'
) except IOError: error = [] return error content = file.readlines() for i in range(len(content)): content[i] = content[i][:len(content[i])-1] file.close() return content

實際使用:

執行
test_text = ['just','for','test']
text_save(test_text,'1.txt')
可以得到一個名為1.txt的文字文件,裡面內容為
just
for
test
現在我們嘗試讀取該檔案
test_content = text_read('1.txt')
print test_content
得到結果為
['just', 'for', 'test']