Python旅途——文件操作

Python——文件操作

1.理解文件操作

  • 可能有的时候有人会在想为什么要对文件进行操作,无论对于文件还是网络之间的交互,我们都是建立在数据之上的,如果我们没有数据,那么很多的事情也就不能够成立,比如我们淘宝买了一件衣服,那么淘宝是如何知道我们的相关信息的呢?为什么不会把我们的衣服发给别人呢?这些都基于我们本身的数据。而我们的数据一般都存放在哪呢?

  • 在我们没有接触数据库之前,我们获得数据的手段也只能是从文件中获取,因此Python中的文件操作也是十分的重要。

2.文件的基本操作

操作文件时,一般需要经历如下步骤

  • 打开文件
  • 操作文件
  • 修改文件
  • 关闭文件

1.打开文件:

  • 文件句柄 = file('文件路径', '模式'),打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
  • 打开文件的模式有:
    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;不存在则创建;存在则只追加内容;】
  • "+"表示可以同时读写某个文件
    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a
  • "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
    • rb
    • wb
    • ab

2.操作文件

  • read() , 全部读到内存

  • read(1)

    • 1表示一个字符

      obj = open('a.txt',mode='r',encoding='utf-8')
      data = obj.read(1) # 1个字符
      obj.close()
      print(data)
      
    • 1表示一个字节

      obj = open('a.txt',mode='rb')
      data = obj.read(3) # 1个字节
      obj.close()
      
  • write(字符串)

    obj = open('a.txt',mode='w',encoding='utf-8')
    obj.write('中午你')
    obj.close()
    
  • write(二进制)

    obj = open('a.txt',mode='wb')
    
    # obj.write('中午你'.encode('utf-8'))
    v = '中午你'.encode('utf-8')
    obj.write(v)
    
    obj.close()
    
  • seek(光标字节位置),无论模式是否带b,都是按照字节进行处理。

    obj = open('a.txt',mode='r',encoding='utf-8')
    obj.seek(3) # 跳转到指定字节位置
    data = obj.read()
    obj.close()
    print(data)
    
    # rb模式
    obj = open('a.txt',mode='rb')
    obj.seek(3) # 跳转到指定字节位置
    data = obj.read()
    obj.close()
    print(data)
    
  • tell(), 获取光标当前所在的字节位置

    obj = open('a.txt',mode='rb')
    # obj.seek(3) # 跳转到指定字节位置
    obj.read()
    data = obj.tell()
    print(data)
    obj.close()
    
  • flush,强制将内存中的数据写入到硬盘

    v = open('a.txt',mode='a',encoding='utf-8')
    while True:
        val = input('请输入:')
        v.write(val)
        v.flush()
    v.close()
    

3. 关闭文件

  • 方式一
v = open('a.txt',mode='a',encoding='utf-8')

v.close()
  • 方式二
with open('a.txt',mode='a',encoding='utf-8') as v:
    data = v.read()
	# 缩进中的代码执行完毕后,自动关闭文件

4. 文件内容的修改

with open('a.txt',mode='r',encoding='utf-8') as f1:
    data = f1.read()
new_data = data.replace('飞洒','666')

with open('a.txt',mode='w',encoding='utf-8') as f1:
    data = f1.write(new_data)
  • 大文件修改(方式一)
f1 = open('a.txt',mode='r',encoding='utf-8')
f2 = open('b.txt',mode='w',encoding='utf-8')

for line in f1:
    new_line = line.replace('大大','小小')
    f2.write(new_line)
f1.close()
f2.close()
  • 大文件修改(方式二)
with open('a.txt',mode='r',encoding='utf-8') as f1, open('c.txt',mode='w',encoding='utf-8') as f2:
    for line in f1:
        new_line = line.replace('阿斯', '死啊')
        f2.write(new_line)

5.with

  • 为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f: 

	...
  • 如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

  • 在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:
    pass
原文地址:https://www.cnblogs.com/guoruijie/p/11055342.html