# 列表数据的读取和写入 # ---------------写入************ list_1 = ['张三','李四','王五'] # 1.打开文件 file_handle = open('student.txt', mode='w') # 2.写入数据 for name in list_1: file_handle.write(name) # 写入换行符 file_handle.write('\n') # 3.关闭文件 file_handle.close() # 读取文件,并且必须是一个列表,格式:['张三','李四','王五'] file_handle = open('student.txt', mode='r') # readlines() 读取所有行的数据,会返回一个列表,列表中存放的数据就是每一行的内容 contents = file_handle.readlines() # 准备一个列表,用来存放取出来的数据 student_list = [] # for循环遍历列表,取出每一行读取到的内容 for name in contents: # strip()去除字符串中的某些特殊字符 去除\n name = name.strip('\n') # 把处理好的name添加到列表中 student_list.append(name) # 这个列表中存放的就是和写入之前一样的内容 print(student_list) # 3.关闭文件 file_handle.close()
#多列表
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(' ') # pop()函数 移除列表中最后一个元素 list_1.pop() # 把小列表添加到大列表中 student_list.append(list_1) file_handle.close() print(student_list)