python學習三(數據保存到文件)


以寫模式打開文件:需要指定寫模式,如下所示

data = open('data.out','w')

 

如果文件已經存在,則會清空它現有的所有內容。要追加一個文件,需要使用訪問模式a,會追加到下一行。

例子:將上節中Man和Other Man說的話,分別保存到兩個文件中

man = []
other = []

try:
    data = open('sketch.txt')

    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':')
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
            else:
                pass
        except ValueError:
            pass

    data.close()
except IOError:
    print('The datafile is missing!')
#使用print將列表中的數據輸出到文件中
try:
    with open('man_data.txt', 'w') as man_file, open('other_data.txt', 'w') as other_file:
        print(man, file=man_file)
        print(other, file=other_file)
except IOError as err:
    print('File error: ' + str(err))

 

使用with open()方法保存文件,不需要再用close方法關閉文件

 

Python提供了一個標准庫,名為pickle,它可以加載、保存幾乎任何的Python數據對象,包括列表

使用python的dump保存,load恢復

import pickle

man = []
other = []

try:
    data = open('sketch.txt')

    for each_line in data:
        try:
            (role, line_spoken) = each_line.split(':')
            line_spoken = line_spoken.strip()
            if role == 'Man':
                man.append(line_spoken)
            elif role == 'Other Man':
                other.append(line_spoken)
            else:
                pass
        except ValueError:
            pass

    data.close()
except IOError:
    print('The datafile is missing!')

try:
    with open('man_data.txt', 'wb') as man_file, open('other_data.txt', 'wb') as other_file:
        pickle.dump(man, file=man_file)
        pickle.dump(other, file=other_file)
except IOError as err:
    print('File error: ' + str(err))
except pickle.PickleError as perr:
    print('Pickling error: ' + str(perr))
    

 

'wb'中的b表示以二進制模式打開文件

要讀取二進制文件使用'rb'

import pickle
with open('man_data.txt','rb') as readText:
    a_list = pickle.load(readText)
print(a_list)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM