student_list = [['張三','22','110'],['李四','22','110'],['王五','22','110']] ''' # 存儲 student_list = [['張三','22','110'],['李四','22','110'],['王五','22','110']] # 1.打開文件 file_handle = open('student_v2.txt',mode='w') # 2.寫入數據 for student in student_list: # for循環取出小列表中的每一條數據, for msg in student: # 寫入文件 file_handle.write(msg) # 寫入空格 file_handle.write(' ') # 一我的的信息寫入完成,寫入換行符 file_handle.write('\n') # 3.關閉文件 file_handle.close() # 取出 file_handle = open('student_v2.txt',mode='r') contents = file_handle.readlines() # [['張三','22','110'],['李四','22','110'],['王五','22','110']] student_list = [] for msg in contents: msg = msg.strip('\n') # split() 經過某個字符分割字符串,返回的是分割完成後的列表 list_1 = msg.split(' ') print(list_1) # pop()函數 移除列表中最後一個元素 list_1.pop() # 把小列表添加到大列表中 student_list.append(list_1) file_handle.close() print(student_list)
用一個for循環實現:python
聲明保存數據的函數 def save_data(): file_handle = open('students_v2.txt', mode='w') # 2.for循環遍歷大列表 for student in student_list: # 把列表中的數據用 空格分開並拼接爲一個字符串 s = ' '.join(student) # 寫入 file_handle.write(s) file_handle.write('\n') # 讀取數據 # 引入os模塊 import os def read_data(): # 1.判斷文件是否存在 rs = os.path.exists('students_v2.txt') if rs == True: # 2.打開文件 file_handle = open('students_v2.txt', mode='r') # 3.讀取全部行 contents = file_handle.readlines() for msg in contents: # 去除\n msg = msg.strip('\n') # 使用 空格分隔字符串,獲得列表 student = msg.split(' ') # 將小列表添加到大列表中 student_list.append(student)