Python-文件读写
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:woshinidaye 4 5 #读文件 6 ''' 7 read() 每次读取整个文件,它通常用于将文件内容放到一个字符串变量中。如果文件大于可用内存,为了保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。 8 readlines() 之间的差异是后者一次读取整个文件,象 .read() 一样。.readlines() 自动将文件内容分析成一个行的列表,该列表可以由 Python 的 for ... in ... 结构进行处理。 9 readline() 每次只读取一行,通常比readlines() 慢得多。仅当没有足够内存可以一次读取整个文件时,才应该使用 readline()。 10 file = open('user_pwd.txt','r') #r文本文件。rb,表示二进制文件 11 print(file.read())#读取整个文件 12 print(file.read(2)) 13 print(file.readline()) 14 stu1 123 15 print(file.readline(1)) 16 print(file.readline(10)) 17 readline是一行一行读取 18 print(file.readlines())#自动将文件给到列表里面,但是三种方式都有换行符,艹了 19 20 为了保障文件调用以后被正确关闭,需要通过try....finally来完成 21 ''' 22 23 ''' 24 try: #try/finally 25 file = open('user_pwd.txt','r') 26 print(file.read()) 27 finally: 28 if file: 29 file.close() 30 ''' 31 32 ''' 33 try....finally比较麻烦,可以使用with命令完成 34 ''' 35 36 ''' 37 with open('user_pwd.txt','r') as file: 38 print(file.read()) 39 ''' 40 41 #readline:读取一行,以文本形式,2就代表前两列 42 ''' 43 with open('user_pwd.txt','r') as file: 44 print(file.readline()) 45 with open('user_pwd.txt','r',encoding='utf-8') as file: 46 print(file.readline(2)) 47 ''' 48 49 #readlines:以列表的形式读取,2就表示 0 1 两个元素 50 51 ''' 52 with open('user_pwd.txt','r') as file: 53 print(file.readlines()) 54 with open('user_pwd.txt','r') as file: 55 print(file.readlines(2)) 56 ''' 57 #['stu1 123\n', 'stu2 123\n', 'stu3 123\n', 'stu4 123'] 58 #['stu1 123\n'] 59 #三种读取方式都有换行符,另外两种看不到是因为print认为是换行,所以不是\n 60 61 ''' 62 with open('user_pwd.txt','r') as file: 63 list = file.readlines() 64 #去除换行符 65 for i in range(0,len(list)): 66 list[i] = list[i].strip('\n') 67 print(list) 68 ''' 69 70 #写文件 w:写文本文件,wb,写二进制文件 71 ''' 72 with open('user_pwd.txt','w') as file: 73 file.write('stu05 123') 74 with open('user_pwd.txt','r') as read_file: 75 print(read_file.read()) 76 ''' 77 #直接用w,若没有文件,创建一个新文件,然后写新文本进去;若文件存在,清空以后,写入文本文件; 78 #直接可以用a,不过需要注意格式! 79 ''' 80 with open('user_pwd.txt','a') as file: 81 file.write('stu06 123') 82 with open('user_pwd.txt','r') as read_file: 83 print(read_file.read()) 84 ''' 85 86 ''' 87 with open('user_pwd.txt','w') as file : 88 file.writelines(['1','2','3']) 89 with open('user_pwd.txt','r') as read_file: 90 print(read_file.read()) 91 #结果是123 92 93 with open('user_pwd.txt','w') as file : 94 file.writelines('123') 95 with open('user_pwd.txt','r') as read_file: 96 print(read_file.read()) 97 #结果还是123 #readlines接收列表 98 99 with open('user_pwd.txt','w') as file : 100 file.writelines(['stu1 123\n','stu2 123\n','stu3 123\n']) 101 with open('user_pwd.txt','r') as read_file: 102 print(read_file.readlines()) 103 #需要手动指定换行符 104 ''' 105 106 ''' 107 username = input('please enter your username:') 108 password = input('please enter your password:') 109 with open('user_pwd.txt','w') as file : 110 file.writelines([username,password]) 111 with open('user_pwd.txt','r') as read_file: 112 print(read_file.readlines()) 113 #这样写格式还是不对 114 ''' 115 116 ''' 117 username_list = [] 118 username = input('please enter your username:') 119 username_list.append(username) 120 #print(username_list) 121 password_list = [] 122 password = input('please enter your password:') 123 password_list.append(password) 124 #print(password_list) 125 with open('user_pwd.txt','a') as file : 126 for i in range(max(len(username_list),len(password_list))): 127 try: #try的思路可以学习一下,try/except 128 file.write("{}\t{}\n".format(username_list[i],password_list[i])) 129 except IndexError: 130 if len(username_list) > len(password_list): 131 file.write('{}\t\n'.format(username_list[i])) 132 else: 133 file.write('\t{}\n'.format((password_list[i]))) 134 with open('user_pwd.txt','r') as read_file: 135 print(read_file.read()) 136 ''' 137 138 139 #open的模式 140 ''' 141 mode is an optional string that specifies the mode in which the file 142 is opened. It defaults to 'r' which means open for reading in text 143 mode. Other common values are 'w' for writing (truncating the file if 144 it already exists), 'x' for creating and writing to a new file, and 145 'a' for appending (which on some Unix systems, means that all writes 146 append to the end of the file regardless of the current seek position). 147 In text mode, if encoding is not specified the encoding used is platform 148 dependent: locale.getpreferredencoding(False) is called to get the 149 current locale encoding. (For reading and writing raw bytes use binary 150 mode and leave encoding unspecified.) The available modes are: 151 ''' 152 153 154 ''' 155 ========= =============================================================== 156 Character Meaning 157 --------- --------------------------------------------------------------- 158 'r' open for reading (default) 159 'w' open for writing, truncating the file first 160 'x' create a new file and open it for writing 161 'a' open for writing, appending to the end of the file if it exists 162 'b' binary mode 163 't' text mode (default) 164 '+' open a disk file for updating (reading and writing) 165 'U' universal newline mode (deprecated) 166 ========= =============================================================== 167 168 The default mode is 'rt' (open for reading text). For binary random 169 access, the mode 'w+b' opens and truncates the file to 0 bytes, while 170 'r+b' opens the file without truncation. The 'x' mode implies 'w' and 171 raises an `FileExistsError` if the file already exists. 172 ''' 173 174 with open('song.txt','r',encoding='utf-8') as f: 175 #print(f.read()) 176 #print('====>',f.read(23)) 177 print(f.readline(3)) 178 ''' 179 for line in f: 180 #print(line) 181 print(line.rstrip()) 182 #print(line,end='') 183 ''' 184 #print(f.readlines()) 185 print(f.closed) #查看文件是否被关闭
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言