Python-------文件操作

这篇博客详细介绍了Python中文件的打开、操作和关闭,包括读写模式的选择、文件指针的位置管理、with语句的使用,以及大文件读取和文件路径处理的方法。还涉及到os模块的环境变量和文件系统操作。

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

1.文件的打开,操作,关闭

打开文件:

 f=open('/etc/passwd1')   ##如果文件不存在,open()函数就会抛出IOError的错误,

print(f)                                       并且给出错误码和详细的信息告诉你文件不存在

操作:

content =f.read()

print(content)

f.readline

f.readlines

读取文件所有内容,返回一个列表,列表元素分别为文件内容

对每一行,去掉后面的‘\n’(列表生成式,map)

print(list(map(lambda   x:   x.strip() ,  f.readlines())))

print([line.strip() for line  in  f.readlines()])

f.readable

写操作:

f.write("hello")

f.write()       ##从指针所在位置写入,写入是字符串内容

f.writelines()    ##将列表里面的每个元素写入文件

f.writable

文件拥有权限判断:

print(f.readable())

print(f.writable())       ##返回 True或者False

文件的关闭:

f.close()

2.文件的读写

f.read()         ##读取文件的全部内容

f=open('/root/test.jpg','rb')   ##读取二进制文件,如图片,视频等用‘rbb’模式打开

import   codecs

with codecs.open('User/michael/gbk.txt','r','gbk') as f:  ##读取非ASCII编码文件

f.read()

文件读取模式选择

r          ##以读的方式打开,定位到文件开头,默认的mode;文件不存在会报错

r+        ##以读写的方式打开,定位到文件开头,可以写入内容到文件;文件不存在会报错

w         ##以写的方式打开,打开文件的时候 会清空文件内容,并且不能读;文件不存在不会报错

w+       ##以读写的方式打开,定位到文件开头并且打开时会清空文件内容;文件不存在不会报错

a          ##以写的方式打开,定位到文件末尾,不允许读

a+         ##以读写的方式打开,定位到文件末尾,追加的方式

在使用mode打开文件时,如果增加了b模式表示以二进制方式打开

如果读取图片,音乐,视频则为rb  , rb+  ,wb   ,wb+   ab   ,ab+

f1=open("frame1.png",mode='rb')

content=f1.read()

print(content)

f1.close()

f2=open("frame1.png",mode='wb')

content=f2.read()

print(content)

f2.close()

3.指针所在位置

print(f.tell( ))

print('1:' , f.read(3))

print("移动指针之前:",f.tell( ))

f.seek(0,0)             ##将文件指针移动到文件最开始

f.seek(0,2)             ##将文件指针移到文件最后

print("移动指针之后:",f.tell( ))

f .write("ptest")

print('2', f.read( ))

f.close( )

4.with语法

一般情况打开一个文件,经过操作之后,都要显示的执行xx.close( )将文件关闭。

with用于需要打开,关闭成对的操作可以自动关闭打开对象。

打开文件,执行完with语句内容之后,自动关闭文件对象

with   open   ('/tmp/passwd')   as  if:

        print("with语句里面:". f.closed)

         prrint(f .read)

print("after   with语句:", f.closed)

 

with   open   ('/tmp/passwd')  as  f1.open('/tmp/passwdBack','w+')  as  f2: ##同时打开两个文件对象

f2.write(f1.read( ))                 ##将第一个文件内容写入第二个文件  

f2.seek(0,0)                          ##将指针移动到文件最开始

print(f2.read( ))                ##读取指针内容

python2不支持这种写法

with  open   ('/tmp/passwd')   as  f1:

        content=f1.read( )

with  open('/tmp/passwdBack', 'w+')

        f2.write(content)

 

5.yielid实现大文件的读取

def   byLineReader(filename):

       with  open(filename)  as  f:

               line=f.readline()           ##如果可以读取到内容返回改行信息

               while   line:

                         yield   line

                         line=f.readline()

read=byLineReader('data.txt')              ##read是一个生成器对象

print(read)

print(next(read))            ##next读取生成器的内容

6.文件对象是可以for循环遍历的,默认遍历的内容为每一行的是节省内存空间

from  collections   import   Iterable

f =open('data.txt')

print(isinstance(f.Iterable))

for  i,item    in   enumerate(f):

            if  i==10:

                break

              print(i,item)

7.读取文件方式效率比较

@timeit

def   read1(filename):                   ##迭代

     with   open(filename)  as  f:      

         for  line  in  f:

            line.split(' : ')            ##对文件处理操作

@timeit

def   read2(fiename):  

         with  open(filename)  as  f:

                 for   line   in  f.readlines():

                         line.split(' : ')

8._os之环境变量函数

import    os

print(os.name)

print('linux'  if  os.name=='posix'  else  'Windows')

##返回值为posix是Linux操作系统,值为nt是Windows操作系统

操作系统的详细信息

info=os.uname( )

print(info)

print( info.sysname)

print(info.nodename)

系统环境变量

print( os.environ)

通过key值获取环境变量对应的value值

print(os.environ.get('PATH'))

print(os.getenv('PATH'))

判断是否为绝对路径

import   os

print(os.path.isaba('/tmp/hello'))

print(os.path.isabs('hello'))

print(os.path.abspath('/tmp/hello'))                

print(os.path.abspath('hello'))           ##生成绝对路径

print(os.path.join('/home/kiosk','hello.png')) 

print(os.path.join(os.path.abspath(','),'hello.png'))      ##返回一个绝对路径,当前目录的绝对路径+文件名/目录名

执行结果

获取文件名或目录名

filename='/home/kiosk/201808python/day10/hello.png'

print(os.path.basename(filename))

print(os.path.dirname(filename))

创建目录/删除目录

os.mkdir('img')

os.rmdir('img')

os.makedirs('img/films')

创建文件/删除文件

os.mknod('00_ok.txt')

os.remove('00_ok.txt')

文件重命名

os.rename('data.txt','data1.txt')

判断文件或者目录是否存在

print(os.path.exists('img'))

分离后缀名和文件名

print(os.path.splitext('hello.png'))

print(os.path.split('hello.png'))

将目录名和文件名分离

print(os.path.split('/tmp/hello/hello.png'))

例:在当前目录新建目录img。里面包含100个文件100个文件名各不相同

     将当前img.以.png结尾的后缀改名为.jpg

生成一个大文件ips.txt要求12000行,每行随即为172.25.254.0/24段的ip

读取ips.txt文件统计这个文件中出现频率排前的10个ip;

import random
def Creat_ips_file(filename):
    ips = ['172.25.254.' + str(i) for i in range(1, 255)]
    with open(filename, 'w') as file_ip:
        for count in range(12000):
            file_ip.write(random.sample(ips, 1)[0] + '\n')
def Sorted_count_ip(filename, count=10):
    ips_dict = dict()
    with open(filename) as file_ip:
        for IP in file_ip:
            if IP in ips_dict:
                ips_dict[IP] += 1
            else:
                ips_dict[IP] = 1
    sorted_ip = sorted(ips_dict.items(), key=lambda x: x[1], reverse=True)[:count]
    return sorted_ip
Creat_ips_file('IP_FILE.txt')
for IP in Sorted_count_ip('IP_FILE.txt', 10):
    print(IP[0])

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值