python 文件操作

本文详细介绍了在编程中如何进行文件操作,包括文件的打开、读取、写入、关闭等基本流程,以及seek、tell、flush、truncate等高级操作。通过实例展示了不同场景下文件操作的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件操作对编程语言的重要性不用多说,如果数据不能持久保存,信息技术也就失去了意义

一、文件处理的一个流程

     1)打开一个文件,得到文件句柄并赋值给一个变量

     2)通过句柄对文件进行操作

     3)关闭文件

     代码:

 file = open("D:/rxz/a.txt",encoding="utf-8") 
 data = file.read() 
 print(data)  
 file.close()

 

二、基本操作

    1、open

    使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。

    代码:

file_object = open(‘a.txt’)
     try:
          all_the_text = file_object.read( )
     finally:
          file_object.close( )

     注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。

    2、读文件(读的文件内容必须全部是字符串)

     1)读文本文件

file= open('a.txt', 'r')
#第二个参数默认为r
file1= open('a.txt')

     2) 读二进制文件

input = open('a.txt', 'rb')

     3)读取所有内容

file = open("D:/rxz/a.txt",encoding="utf-8")
try:
     data = file.read( )
     print(data)
finally:
    file.close( )

    4)读固定字节

file = open("D:/rxz/a.txt",encoding="utf-8")
try:
    while True:
     data = file.read(100 )
     print(data)
     if not data:
         break
finally:
    file.close( )

     5)把文件的所有内容都读取出来,放入一个列表中

file = open("D:/rxz/a.txt",encoding="utf-8")
try:
     list_of_all_the_lines = file.readlines()
     print(list_of_all_the_lines)
finally:
    file.close( )

    如果文件是文本文件,还可以直接遍历文件对象获取每行: 

file = open("D:/rxz/a.txt",encoding="utf-8")
for line in file:
    print(line)

  6)一行一行的

file = open("D:/rxz/a.txt",encoding="utf-8")
print(file.readable())  #判断是否可读
print("第1行",file.readline(),end="")
print("第2行",file.readline())
print("第3行",file.readline())
print("第4行",file.readline())
print("第5行",file.readline())
file.close()

#结果:
True
第1行 1111111111
第2行 22222222222

第3行 3333333333

第4行 44444444444

第5行 55555555555

3、写文件(写的文件内容必须全部是字符串)

    1)写文本文件

output = open('D:/rxz/a.txt', 'w')
content = "展开白色的平面\n升起雾生起露"
data = output.write(content)


file = open("b.txt","w",encoding="utf-8")
file.write("11111111111\n")
file.write("22222222222")
file.close()

   2)写二进制文件

output = open('D:/rxz/a.txt', 'wb')

   3)追加写文件

file = open("b.txt","a",encoding="utf-8")
file.write("写到文件的最后")
file.close()

   4)写数据

file_object = open('D:/rxz/a.txt', 'w')
content = "展开白色的平面\n升起雾生起露"
file_object.write(content )
file_object.close( )

 

   5)写一个列表,列表有内容

file_object = open('D:/rxz/a.txt', 'w')
file_object.writelines(["展开白色的平面\n","升起雾生起露\n","展开白色的平面\n","升起雾生起露"])
file_object.close( )

   6)既能读也能写

file_object = open('D:/rxz/a.txt', 'r+',encoding = "gbk)
data = file_object .read()
print(data)
file_object .write("123456")
file_object.close( )


 #写的时候只从光标那里开始写

  7)补充

# 用with open进行操作就不需要在写f.close()这个操作,因为with open函数已经自动帮你实现关闭文件的操作
with open(“a.txt”,"w")as f:
        f.write("111111\n")

# 用with open可以发开多个文件
with open("a.txt","r",encoding ="gbk") as src_f, \
     open("a_new.txt","w",endcoding = "gbk") as dst_f:
      data = src_f.read()
      dst_f.write(data)
     

4、其它方式

     1)flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。

文件的内容从内存刷入硬盘中

fo = open("a.txt", "wb")
print("文件名为: ", fo.name)
fo.write("1111111")
 
# 刷新缓冲区
fo.flush()
 
# 关闭文件
fo.close()
     

2) tell 

    1. 作用:获取当前文件读取指针的位置

    2. 语法格式: file.tell() 注: 此方法没有参数

fo = open("a.txt", "wb")
print("文件名为: ", fo.name)
print(fo.x.tell())  
fo.write("1111111")
print(fo.x.tell())  
 
# 关闭文件
fo.close()
     

  补充:

      1)一汉字等于3个字节,windows换行本来“\r\n”,但是由于Python编译器会把"\r"去掉,解决这个办法newline=""

output = open('D:/rxz/a.txt', 'r+',encoding="utf-8",newline="")
print(output.readlines())

#结果
['11111111\r\n', '22222222\r\n', '333333']
     

        2) read(3)代表读取3个字符,其余的文件内光标移动都是以字节为单位,如:seek,tell,read,truncate

 

3) seek   控制光标的移动

     1. 作用:用于移动文件读写指针到指定的位置

     2. 语法格式:file.seek(offset, whence=0):       

         offset: 偏移量,需要向前或者是向后移动的字节数

         whence: 可选值,默认为0, 可选值为1或者2,表示从何处开始计算偏移,具体来说,

>>> x = file('my.log', 'r')	#读取一个文件
>>> x.tell()			#获得当前文件读取指针
0L				#当前文件指针在文件头处
>>> x.seek(3)			#将文件指针向前移动3个字节
>>> x.tell()
3L				#指针已经移动到了第3个字节处
>>> x.seek(5,1)			#表示从文件头处开始移动指针,向前移动5个字节
>>> x.tell()				
5L				#当前文件读取指针已经移动到第5个字节处
>>> x.seek(0,0)			#表示将文件指针移动到文件头处
>>> x.tell()
0L
>>> x.seek(0,2)			#表示将文件读取指针移动到文件尾部
>>> x.tell()				
214L				#可以得到文件大小为214B
>>> x.seek(-2,2)		#表示从文件尾部开始移动指针,向后移动2个字节
>>> x.tell()
212L
     

 # 基于相对 

f = open("seek.text","rb") 
print(f.tell()) 
f.seek(10,1) # 1代表相对于上个位置 
print(f.tell()) 
f.seek(3,1) # 1代表相对于上个位置(10) 
print(f.tell())


#结果
0
10
13

 #倒叙位置 

f = open("seek.text","rb")
print(f.tell())
f.seek(-10,2) # 倒着的10个字符
print(f.read())
print(f.tell())


#结果
0
b'\r\n\xe4\xbd\xa0\xe5\xa5\xbd\r\n'
33

 

# 读取文件最后一行
# 读取文件最后一行
f = open("b.txt","rb")
for i in f:
    offs = -10
    while True:
        f.seek(offs,2)
        data = f.readlines()
        if len(data) >1:
            print("文件的最后一行%s" %(data[-1].decode("utf-8")))
            break
        offs *= 2

 4) truncate   文件必须以写方式打开,但是w和w+除外(因为这种格式打开文件会清空文件的内容)

     1.作用:      用于截断文件并返回截断的字节长度

     2. 语法格式: fileObject.truncate([size])

          size -- 可选,如果存在则文件从开头截断为指定字节。

指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除。该方法没有返回值。

fo = open("a.txt", "r+", encoding="utf-8")
print ("文件名: ", fo.name)
 
fo.seek(36)
fo.truncate()  # 从第36个字节以后的内容全部删除了
fo.seek(0,0)
line = fo.readlines()
print("读取行: %s" % (line))
fo.truncate(10)  # 截取10个字节
fo.seek(0,0)
str = fo.read()
print("读取数据: %s" % (str))
 
# 关闭文件
fo.close()

#结果
文件名:  a.txt
读取行: ['1:www.baidu.com\n', '2:www.baidu.com\n']
读取数据: 1:www.baid
     

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值