f = open('小重山') #打开文件data=f.read()#获取文件内容f.close() #关闭文件 ,如果没有关闭,那在写文件的话,只到缓存,没有到硬盘。
注意 if in the win,hello文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统默认的是gbk编码,所以直接打开会乱码,需要f=open('hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。
1|21.2 文件打开模式
========= ===============================================================
Character Meaning
--------- --------------------------------------------------------------- 'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a newfileandopen it for writing
'a'openfor writing, appending to the endof the fileif it exists'b'binarymode't'textmode (default)
'+'open a disk filefor updating (reading and writing)
'U' universal newlinemode (deprecated)
========= ===============================================================
先介绍三种最基本的模式:r(只可读) w(只可写) a(追加)
# f = open('小重山2','w') #打开文件,清空后再写# f = open('小重山2','a') #打开文件,追加# f.write('莫等闲1\n')# f.write('白了少年头2\n')# f.write('空悲切!3')
1|31.3 文件具体操作
defread(self, size=-1):# known case of _io.FileIO.read"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""return""defreadline(self, *args, **kwargs):passdefreadlines(self, *args, **kwargs):passdeftell(self, *args, **kwargs):# real signature unknown"""
Current file position.
Can raise OSError for non seekable files.
"""passdefseek(self, *args, **kwargs):# real signature unknown"""
Move to new file position and return the file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file).
Note that not all file objects are seekable.
"""passdefwrite(self, *args, **kwargs):# real signature unknown"""
Write bytes b to file, return number written.
Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""passdefflush(self, *args, **kwargs):passdeftruncate(self, *args, **kwargs):# real signature unknown"""
Truncate the file to at most size bytes and return the truncated size.
Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""passdefclose(self):# real signature unknown; restored from __doc__"""
Close the file.
A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""pass##############################################################less usefulldeffileno(self, *args, **kwargs):# real signature unknown""" Return the underlying file descriptor (an integer). """passdefisatty(self, *args, **kwargs):# real signature unknown""" True if the file is connected to a TTY device. """passdefreadable(self, *args, **kwargs):# real signature unknown""" True if file was opened in a read mode. """passdefreadall(self, *args, **kwargs):# real signature unknown"""
Read all data from the file, returned as bytes.
In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""passdefseekable(self, *args, **kwargs):# real signature unknown""" True if file supports random-access. """passdefwritable(self, *args, **kwargs):# real signature unknown""" True if file was opened in a write mode. """pass操作方法介绍
操作方法源码
f = open('小重山') #打开文件
# data1=f.read()#获取文件内容# data2=f.read()#获取文件内容##print(data1)#print('...',data2)# data=f.read(5)#获取文件内容,汉字在这里占一个单位(in Py3)# data=f.readline() #无论是read()还是readline(),光标会发生位置变化#print(f.__iter__().__next__())#for i in range(5):#print(f.readline())# data=f.readlines()['昨夜寒蛩不住鸣。\n', '惊回千里梦,已三更。\n', '起来独自绕阶行。\n', '人悄悄,帘外月胧明。\n', '白首为功名,旧山松竹老,阻归程。\n', '欲将心事付瑶琴。\n', '知音少,弦断有谁听。']#for line in f.readlines():#print(line)# 问题来了:打印所有行,另外第3行后面加上:'end 3'#for index,line in enumerate(f.readlines()):#if index==2:# line=''.join([line.strip(),'end 3'])#print(line.strip())#切记:以后我们一定都用下面这种# count=0 #for line in f: # 这是for内部将 f 对象做成一个迭代器,用一行去一行。#if count==3: # line=''.join([line.strip(),'end 3'])#print(line.strip())# count+=1#print(f.tell())#print(f.readline())#print(f.tell()) #tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.#print(f.read(5)) #一个中文占三个字节#print(f.tell())# f.seek(0) #跟tell相对,人为设定位置#print(f.read(6)) #read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符#terminal上操作:f = open('小重山2','w')
# f.write('hello \n')# f.flush() #flush():同步把将数据从缓存转移到磁盘上去# f.write('world')# 应用:进度条# import time,sys#for i in range(30):# sys.stdout.write("*")## sys.stdout.flush()# time.sleep(0.1)
# import sys,time # for i in range(30): # print('*',end='',flush=True) # time.sleep(0.1)
withopen('log1') as obj1, open('log2') as obj2:
pass
1|51.5 修改文件
# 修改文件withopen('小护士班主任',encoding='utf-8') as f,open('小护士班主任.bak','w',encoding='utf-8') as f2:
for line in f:
if'星儿'in line: #班主任:星儿 line = line.replace('星儿','啊娇')
#写文件 f2.write(line) #小护士:金老板import os
os.remove('小护士班主任') #删除文件os.rename('小护士班主任.bak','小护士班主任') #重命名文件
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!