文件读写

之前没有学习字符串操作,学习文件操作有点懵逼,重新学习一下,毕竟对于小教本而言,变量不多,可以用内存帮忙实现,但是很多时候要实现持久化,或者减轻内存的压力,熟练使用文件读写还是很有必要的

复制代码
  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 # Author:woshinidaye
  4 #
  5 
  6 '''
  7 f = open('price_tag',encoding='utf-8')  #文件句柄 Handle       #默认r模式,只读
  8 read_1 = f.read()
  9 read_2 = f.read()
 10 print(read_1)
 11 print('>>>>>>>',read_2)     #read_2居然是空的!因为句柄的概念,read_1读完以后,就到了文件最后,此时read_2接着读就是空的
 12 '''
 13 print('parting_1'.rjust(25,'>').ljust(50,'<'))
 14 #f.write('let us test~~')            #报错了,io.UnsupportedOperation: not writable
 15 #这是因为,文件打开的时候是只读(默认),需要在打开时指定
 16 
 17 '''
 18 f = open('price_tag_2','w',encoding='utf-8')      #w模式,只写,若存在同名文件,会被覆盖!!一定要小心,可理解为创建一个同名新文件!!!
 19 f.write('let us test1!!\n')
 20 f.write('let us test2!!')
 21 f = open('price_tag_2','a',encoding='utf-8')    #a,append,只能添加,也不能读,不覆盖之前的文件
 22 f.write('let us test3\n')       #没执行一次,文件price_tag_2最后就多一行,
 23 '''
 24 print('parting_2'.rjust(25,'>').ljust(50,'<'))
 25 
 26 '''
 27 f = open('price_tag','r',encoding='utf-8')
 28 print(f.readline().rstrip())
 29 print(f.readline())
 30 print(f.readline())     #我在这里写了三次,发现就是每次读一行,光标到了一行末尾以后接着网下一行读,每次的结果都不一样
 31                         #他把换行符也读出来了,可以通过字符串处理办法取消了末尾的换行符
 32 for i in range(20):
 33     print(f.readline().rstrip())
 34 f.close()'''
 35 print('parting_3'.rjust(25,'>').ljust(50,'<'))
 36 
 37 
 38 
 39 f = open('price_tag','r',encoding='utf-8')
 40 #print(f.readlines(),'\n',type(f.readlines()))   #readlines读出来是一个列表!
 41 '''for index,line in enumerate(f.readlines()):
 42     if index+1 == 15:
 43         print('this is a line which i discard') #不打印文本第14行,index+1了,所以结果应该是index=15
 44         continue
 45     print(index+1,line.strip())'''
 46 f.close()
 47 print('parting_4'.rjust(25,'>').ljust(50,'<'))
 48 
 49 #但是readlines和read有个致命的问题,他是一次性把文件读到内存中,那如果一个2G的大文件,可能直接把环境搞崩。readlines只能用于小文件。。。
 50 #可以尝试读一行就删除一行,这样内存中仅保留几行数据,这样对内存的压力就很小了
 51 '''
 52 f = open('price_tag','r',encoding='utf-8')
 53 count = 1
 54 for line in f:
 55     if count == 14:
 56         print('this is a line which i discard') #不打印文本第14行
 57         #count = count + 1
 58         continue
 59     print(line.rstrip(),type(line))                    #这个的读取效率才是最高的,推荐使用
 60     count = count + 1
 61 f.close()
 62 print(f.closed)
 63 '''
 64 print('parting_5'.rjust(25,'>').ljust(50,'<'))
 65 
 66 '''
 67 f = open('price_tag','r',encoding='utf-8')
 68 print(f.readline())         #读完这一行之后,光标就到了一行的最后面,可通过f.tell查看,tell是按照字符计算
 69 print(f.tell())
 70 f.seek(0)                   #将光标回到开头
 71 print(f.readline())
 72 f.close()
 73 '''
 74 print('parting_6'.rjust(25,'>').ljust(50,'<'))
 75 
 76 
 77 #f.buffer   默认文件写入是先存在一部分内存中,存到buffer大小以后,再往盘上写数据,有时为了让数据立马写入次磁盘,需要将强制刷新一下
 78 #f.flush()  强制写到磁盘中。
 79 #借助flush的思想,可以思考一下进度条,‘#’可以实现一个‘#’一个‘#’的输入,刷新,打印,就出现了进度条的效果
 80 
 81 '''import sys,time
 82 g = open('price_tag_2','w',encoding= 'utf-8')
 83 for i in range(50):
 84     sys.stdout.write('#')
 85     sys.stdout.flush()
 86     time.sleep(0.2)
 87 g.close()'''
 88 print('parting_7'.rjust(25,'>').ljust(50,'<'))
 89 
 90 
 91 #    ========= ===============================================================
 92 #    Character Meaning
 93 #    --------- ---------------------------------------------------------------
 94 #    'r'       open for reading (default)
 95 #    'w'       open for writing, truncating the file first
 96 #    'x'       create a new file and open it for writing
 97 #    'a'       open for writing, appending to the end of the file if it exists
 98 #    'b'       binary mode
 99 #    't'       text mode (default)
100 #    '+'       open a disk file for updating (reading and writing)
101 #    'U'       universal newline mode (deprecated)
102 #    ========= ===============================================================
103 
104 '''
105 f = open('price_tag_2','w+',encoding='utf-8')       #mode:写读模式。会把老子之前的同名文件删掉,建立一个新文件,太坑了
106 print(f.readline())
107 f.write('=====>>>>>><<<<<<=====')
108 print(f.tell())
109 f.seek(0)
110 print(f.readline())
111 '''
112 
113 
114 '''
115 h = open('price_tag_2','r+',encoding='utf-8')
116 print(h.read())
117 print(h.readline().rstrip())
118 print(h.readline().rstrip())
119 print(h.tell())
120 h.write('======testing====')
121 print(h.read())         #如果没有吧光标移动到前面,是读不到任何东西的,因为写是写在最后面,写完以后,光标就落到了最后
122 h.seek(0)
123 print(h.readline())         #没有移动光标的位置的话,是没法读到信息的
124 '''
125 #写的话,是没办法在文本中间进行修改的!!
126 '''
127 f = open('price_tag_2','wb')
128 f.write('hello~~!@#SCHNSADFGH'.encode())
129 f.close()
130 '''
131 print('parting_8'.rjust(25,'>').ljust(50,'<'))
132 
133 #文件的修改:把硬盘中的文件---->内存---->修改----->写入硬盘,vim
134 #修改方法2:方法一台占用内存了,可以只在内存中保留一行文件,然后对选中的某一行进行特定化修改,修改之后写到新文件中。
135 
136 f = open('price_tag_2','r',encoding='utf-8')
137 f_new = open('price_tag_new','w',encoding='utf-8')
138 for line in f:
139     if '夜晚' in line:
140         line = line.replace('夜晚','清早八晨')
141     f_new.write(line)
142 f.close()
143 f_new.close()
144 print('parting_9'.rjust(25,'>').ljust(50,'<'))
145 
146 
147 #为了避免打开文件后,忘记关闭文件,导致文件异常,建议使用with命令
148 with open('price_tag_2','r',encoding='utf-8') as f:
149     #print(f.readline())
150     for line in f:
151         print(line.rstrip())
152 with open('price_tag_2','r',encoding='utf-8') as f,open('price_tag','r',encoding='utf-8') as h:
153     pass
154 print('ending'.rjust(25,'>').ljust(50,'<'))
复制代码

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:woshinidaye
#

'''
f = open('price_tag',encoding='utf-8') #文件句柄 Handle #默认r模式,只读
read_1 = f.read()
read_2 = f.read()
print(read_1)
print('>>>>>>>',read_2) #read_2居然是空的!因为句柄的概念,read_1读完以后,就到了文件最后,此时read_2接着读就是空的
'''
print('parting_1'.rjust(25,'>').ljust(50,'<'))
#f.write('let us test~~') #报错了,io.UnsupportedOperation: not writable
#这是因为,文件打开的时候是只读(默认),需要在打开时指定

'''
f = open('price_tag_2','w',encoding='utf-8') #w模式,只写,若存在同名文件,会被覆盖!!一定要小心,可理解为创建一个同名新文件!!!
f.write('let us test1!!\n')
f.write('let us test2!!')
f = open('price_tag_2','a',encoding='utf-8') #a,append,只能添加,也不能读,不覆盖之前的文件
f.write('let us test3\n') #没执行一次,文件price_tag_2最后就多一行,
'''
print('parting_2'.rjust(25,'>').ljust(50,'<'))

'''
f = open('price_tag','r',encoding='utf-8')
print(f.readline().rstrip())
print(f.readline())
print(f.readline()) #我在这里写了三次,发现就是每次读一行,光标到了一行末尾以后接着网下一行读,每次的结果都不一样
#他把换行符也读出来了,可以通过字符串处理办法取消了末尾的换行符
for i in range(20):
print(f.readline().rstrip())
f.close()'''
print('parting_3'.rjust(25,'>').ljust(50,'<'))



f = open('price_tag','r',encoding='utf-8')
#print(f.readlines(),'\n',type(f.readlines())) #readlines读出来是一个列表!
'''for index,line in enumerate(f.readlines()):
if index+1 == 15:
print('this is a line which i discard') #不打印文本第14行,index+1了,所以结果应该是index=15
continue
print(index+1,line.strip())'''
f.close()
print('parting_4'.rjust(25,'>').ljust(50,'<'))

#但是readlinesread有个致命的问题,他是一次性把文件读到内存中,那如果一个2G的大文件,可能直接把环境搞崩。readlines只能用于小文件。。。
#可以尝试读一行就删除一行,这样内存中仅保留几行数据,这样对内存的压力就很小了
'''
f = open('price_tag','r',encoding='utf-8')
count = 1
for line in f:
if count == 14:
print('this is a line which i discard') #不打印文本第14
#count = count + 1
continue
print(line.rstrip(),type(line)) #这个的读取效率才是最高的,推荐使用
count = count + 1
f.close()
print(f.closed)
'''
print('parting_5'.rjust(25,'>').ljust(50,'<'))

'''
f = open('price_tag','r',encoding='utf-8')
print(f.readline()) #读完这一行之后,光标就到了一行的最后面,可通过f.tell查看,tell是按照字符计算
print(f.tell())
f.seek(0) #将光标回到开头
print(f.readline())
f.close()
'''
print('parting_6'.rjust(25,'>').ljust(50,'<'))


#f.buffer 默认文件写入是先存在一部分内存中,存到buffer大小以后,再往盘上写数据,有时为了让数据立马写入次磁盘,需要将强制刷新一下
#f.flush() 强制写到磁盘中。
#借助flush的思想,可以思考一下进度条,‘#’可以实现一个‘#’一个‘#’的输入,刷新,打印,就出现了进度条的效果

'''import sys,time
g = open('price_tag_2','w',encoding= 'utf-8')
for i in range(50):
sys.stdout.write('#')
sys.stdout.flush()
time.sleep(0.2)
g.close()'''
print('parting_7'.rjust(25,'>').ljust(50,'<'))


# ========= ===============================================================
# Character Meaning
# --------- ---------------------------------------------------------------
# 'r' open for reading (default)
# 'w' open for writing, truncating the file first
# 'x' create a new file and open it for writing
# 'a' open for writing, appending to the end of the file if it exists
# 'b' binary mode
# 't' text mode (default)
# '+' open a disk file for updating (reading and writing)
# 'U' universal newline mode (deprecated)
# ========= ===============================================================

'''
f = open('price_tag_2','w+',encoding='utf-8') #mode:写读模式。会把老子之前的同名文件删掉,建立一个新文件,太坑了
print(f.readline())
f.write('=====>>>>>><<<<<<=====')
print(f.tell())
f.seek(0)
print(f.readline())
'''


'''
h = open('price_tag_2','r+',encoding='utf-8')
print(h.read())
print(h.readline().rstrip())
print(h.readline().rstrip())
print(h.tell())
h.write('======testing====')
print(h.read()) #如果没有吧光标移动到前面,是读不到任何东西的,因为写是写在最后面,写完以后,光标就落到了最后
h.seek(0)
print(h.readline()) #没有移动光标的位置的话,是没法读到信息的
'''
#写的话,是没办法在文本中间进行修改的!!
'''
f = open('price_tag_2','wb')
f.write('hello~~!@#SCHNSADFGH'.encode())
f.close()
'''
print('parting_8'.rjust(25,'>').ljust(50,'<'))

#文件的修改:把硬盘中的文件---->内存---->修改----->写入硬盘,vim
#修改方法2:方法一台占用内存了,可以只在内存中保留一行文件,然后对选中的某一行进行特定化修改,修改之后写到新文件中。

f = open('price_tag_2','r',encoding='utf-8')
f_new = open('price_tag_new','w',encoding='utf-8')
for line in f:
if '夜晚' in line:
line = line.replace('夜晚','清早八晨')
f_new.write(line)
f.close()
f_new.close()
print('parting_9'.rjust(25,'>').ljust(50,'<'))


#为了避免打开文件后,忘记关闭文件,导致文件异常,建议使用with命令
with open('price_tag_2','r',encoding='utf-8') as f:
#print(f.readline())
for line in f:
print(line.rstrip())
with open('price_tag_2','r',encoding='utf-8') as f,\
open('price_tag','r',encoding='utf-8') as h:
    pass
print('ending'.rjust(25,'>').ljust(50,'<'))
posted @   woshinidaye  阅读(37)  评论(0编辑  收藏  举报
编辑推荐:
· 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数据库查询与断言
点击右上角即可分享
微信分享提示