Python基础之文件操作

    科技2022-07-13  130

    一、打开和关闭文件

    1.打开文件

    f = open('xxx.txt','w') #以写的方式打开一个文件

    2.关闭文件

    f = open('xxx.txt','w') f.close() #关闭文件

    二、文件的打开模式

    打开模式说明r(read)以只读的方式打开。文件的指针将会放在文件的开头。这是默认的模式w(write)以只写的方式。如果该文件已经存在则将其覆盖。如果不存在,则创建一个文件用于写入。a(append)以追加的方式打开文件。如果该文件存在将新的内容追加到文件末尾。如果不存在,则创建新文件用于写入。rb(read binary)以二进制的并且只读的方式打开一个文件。文件指针将会放在文件的开头。wb以二进制和只写的方式打开一个文件。如果该文件已经存在则将其覆盖。如果该文件不存在,则创建新文件用于写入。ab以二进制和追加的方式打开一个文件。如果该文件已经存在则追加到文件末。如果不存在,则创建新文件用于写入。r+打开一个文件用于读写。文件指针将会放在文件的开头。写进去的内容会覆盖原来的内容。w+打开一个文件用于读写。如果该文件已经存在则将其覆盖。如果文件不存在,则创建新文件。a+打开一个文件用于读写,文件指针将会放在文件的结尾。如果文件存在,则会将新内容追加到文件后面。如果文件不存在,则创建新文件。rb+以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。wb+以二进制格式打开一个文件用于读写。如果该文件已经存在则将其覆盖。如果文件不存在,创建新文件。ab+以二进制格式打开一个文件用于追加。如果该文件已经存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

    三、文件的读写操作

    1.读数据

    使用read(count)函数可以从文件中读取数据,count表示要从文件中读取的数据的长度。如果没有传,那么表示读取文件中的所有的数据。

    fp = open('test.txt','r') # 读取前面5个字节的数据 line = fp.read(5) print(line) # 读取所有的数据 line = fp.read() print(line)

    2.读一行的数据

    使用readline可以以行的形式读取文件。

    fp = open('test.txt','r') line = fp.readline() print('第一行:%s' % line) line = fp.readline() print('第二行:%s' % line) fp.close()

    3.以行的形式把文件中所有的数据都读出来

    readlines返回一个列表,列表中装的就是文件中每行的数据。

    fp = open('test.txt','r') lines = fp.readlines() for line in lines: print(line) fp.close()

    4.直接迭代文件对象 文件对象也是一个迭代器。即可以通过for循环来进行迭代,并且一次性只会读取一行,从而可以读取大文件。

    fp = open('test.txt','r') for line in fp: print(line)

    5.write写数据到文件中

    write将数据写入到文件中。

    fp = open('test.txt','w') fp.write('hello') fp.close()

    6.writelines写多个数据到文件中

    writelines可以一次性写入多个数据,但是不会自动换行。

    fp = open('test.txt','w') fp.writelines(['hello','world']) fp.close()

    四、文件的定位读写

    1.获取当前文件指针的位置

    在读写的过程中,如果想要知道当前文件指针所在的位置,可以通过tell()来获取。

    fp = open('xxx.txt','r') str = fp.read(3) print('读取到的数据是:%s' % str) # 查看当前位置 position = fp.tell() print("当前文件位置:%d" % position) fp.close()

    2.定位到某个位置

    如果在读写文件的过程中,需要从另外一个位置进行操作,可以使用seek()。seek(offset,from)有2个参数,意义为如下:

    offset:偏移量。

    from:相对位置。

    0:表示从文件开头。

    1:表示从当前位置。

    2:表示从文件末尾。 但是在Python3中,如果from的值不是等于0,那么offset就必须为0。

    # demo1:把相对位置设置为从文件开头,并且向后偏移5个字节。 fp = open("xxx.txt","r") position = fp.tell() print("当前文件指针位置是:%d" % position) fp.seek(5,0) position = fp.tell() print('当前位置是:%d' % position) str = fp.read() print('读取到的字符串:%s' % str) # demo2:把位置设置为:离文件末尾,3个字节处 fp = open("xxx.txt","r") # 查看当前位置 pos = fp.tell() print('当前文件指针位置:%d' % pos) # 重新设置位置为离文件末尾3个字节位置,会报错 # fp.seek(-3,2) fp.seek(0,2) fp.seek(fp.tell()-3,0) # 读取数据 str = fp.read() # 关闭文件 fp.close()

    五、关闭文件

    通常来说,一个文件对象在退出程序后会自动关闭。但是对于一些你写入了数据的文件,应该手动的进行关闭。因为Python可能会缓存写入的输入,如果程序抛出异常,那么缓存的文件将不会被写入文件。因此为了安全起见,要在使用完文件后关闭。 一般的写法是:

    fp = open("xxx.txt",'r') try: # your code finally: # 为了安全起见,不管程序有没有发生异常,都要关闭文件 fp.close() #实际上,有专门为这种情况设计的语句,即with语句: with open('xxx.txt','r') as fp: # your code

    以上的with语句,不管程序有没有发生异常,都会关闭文件。with语句是叫做上下文管理器,上下文管理器是一种支持__enter__和__exit__这两个方法的对象。后期会讲到。以后在使用文件操作的时候,应该尽量使用with语句。

    六、简单的demo

    1.文件的copy

    with open('xxx.txt','r') as fp1: with open('xxx[copy].txt','w') as fp2: for line in fp1: fp2.write(line)

    2.去掉符合标准的段落

    LINES = [] with open('test.html','r') as fp: is_virus = False for line in fp: if line.startswith('<script type="text/vbscript">'): is_virus = True elif line.startswith('</script>'): is_virus = False else: if not is_virus: LINES.append(line) with open('test.html','w') as fp: fp.writelines(LINES)

    3.实现一个宠物寄养管理系统,要求如下

    需要使用函数来模块化。宠物的信息包括:宠物编号/宠物名称/宠物种类/一天的价格。需要实现:添加/查找/删除/退出程序的功能。要求使用文件来存储信息,下次打开系统,数据依然存在。 PETS = [] FILENAME = 'pets.txt' try: with open(FILENAME,'r',encoding='utf-8') as fp: for line in fp: info = line.split("/") ID = info[0] name = info[1] category = info[2] price = info[3] PETS.append({'id':ID,'name':name,'category':category,'price':price}) except FileNotFoundError: fp = open(FILENAME,'w',encoding='utf-8') fp.close() def add_pet(): ID = input('请输入宠物编号:') name = input("请输入宠物名称:") category = input("请输入宠物种类:") price = input("请输入宠物价格:") pet = {"id":ID,'name':name,'category':category,'price':price} PETS.append(pet) print("恭喜!宠物添加成功!") def search_pet(): name = input("请输入宠物名称:") for pet in PETS: if pet['name'] == name: text = "编号:{},名称:{},种类:{},价格:{}".format( pet['id'], pet['name'], pet['category'], pet['price'] ) print(text) def delete_pet(): ID = input("请输入宠物的编号:") for pet in PETS: if pet['id'] == ID: PETS.remove(pet) print("恭喜!宠物删除成功!") break def list_pet(): for pet in PETS: text = "编号:{},名称:{},种类:{},价格:{}".format( pet['id'], pet['name'], pet['category'], pet['price'] ) print(text) def exit_programe(): with open(FILENAME,'w',encoding='utf-8') as fp: lines = [] for pet in PETS: text = "{ID}/{name}/{category}/{price}".format( ID = pet['id'], name = pet['name'], category = pet['category'], price = pet['price'] ) lines.append(text+'\n') fp.writelines(lines) def main(): print('='*30) print('1. 添加宠物。') print('2. 查找宠物。') print('3. 删除宠物。') print('4. 列出宠物。') print("5. 退出程序。") print('='*30) while True: option = input("请输入选项:") if option == '1': add_pet() elif option == '2': search_pet() elif option == '3': delete_pet() elif option == '4': list_pet() elif option == '5': exit_programe() break else: print("请输入正确的选项!") main()
    Processed: 0.025, SQL: 8