Day2_and_Day3 文件操作

文件修改操作:

文件的修改操作:文件并没有修改操作,实际是将一个编写的新文件覆盖了原有的文件

替换文件中的某个内容:

with open('old.txt','r',encoding='utf-8') as read_f,

  open('.old.txt.swap',swap,'w',encoding='utf-8') as write_f:

  msg=read_f.read()

  msg=msg.replace('alex','SB')

  print(msg)

  wirte_f.write(msg)

os.remove('old.txt')  #删除原有的文件

os.rename('.old.txt.swap','old.txt')  #将交换文件替换为原有的文件

然后再替换回来:

with open('old.txt','r',encoding='utf-8') as read_f,

  open('.old.txt.swap',swap,'w',encoding='utf-8') as write_f:

  for line in read_f:

    if 'SB' in line:

      line=line.replace('SB','alex')

    write_f.write(line)

os.remove('old.txt')  #删除原有的文件

os.rename('.old.txt.swap','old.txt')  #将交换文件替换为原有的文件

字符编码:把人类的字符翻译成计算机能认识的数字。

字符编码表:就是一张字符与数字对应关系的表

eg:

  ascii

   gbk

  utf-8

   unicode unicode---->encode('utf-8')------>bytes

   bytes------>decode('utf-8')------>unicode

原则:字符以什么格式编译的,就要以什么格式解码。
  python3中字符串分为两种: x='egon' 存成unicode y=x.encode('utf-8')存成bytes
  python2中字符串分为两种: x=u'egon'与python3中的字符串是一样的 y='alex'与python3中的bytes一样


f=open('a.txt','r',encoding='utf-8')

  #当文件不存在的时候,不会创建文件,会报错 f.read()

  #向操作系统发起调用

b模式:即直接从硬盘中读取bytes

  f=open('a.txt','rb') print(f.read().decode('utf-8'))
写模式: f=open('a.txt','w',encoding='utf-8')

  w文本模式的写,文件存在则清空,不存在的话则创建

  f.write('aaaa ') f.write('bbb ')

#写一行 f.newlines('111111 ','sdsa ')

#写多行 a文本追加模式,文件不存在创建,文件存在将光标移到最后一行 f=open('b.txt','a',encoding='utf-8')

r+,w+,a+ 分别代表读的时候可以写,写的时候可以读,追加的时候可以读。
  rb模式即直接从硬盘中读取bytes f=open('a.txt','rb') print(f.read())

wb模式,写入的时候以二进制写入 f=open('a.txt','wb') f.write('你真红'.encode('utf-8'))
  对于图片或者对于其他不是字符文件的复制操作:

f=open('test.jpg','rb')
print(f.read())
with open('test.jpg','rb') as read_f,open('test1.jpg','wb') as write_f:
    for line in read_f:
        write_f.write(line)


#写一个小程序

import sys
#python3 copy.py source.file target.file
if len(sys.argv) < 3:
    print('Usage:python3 copy.py source.file target.file')
    sys.exit()
with open(r'%s'%sys.argv[1],'rb') as read_f,open(r'%s'%sys.argv[2],'wb') as write_f:
    for line in read_f:
        write_f.write(line)


因为在window中涉及路径的问题,当存在的时候可能会使某些字符失效。所以就利用 r 来进行转义。

用法: r%s %sys.argv 这样

文件内光标的移动:

  1,文件打开方式为文本模式打开时,代表读取三个字符。

  f=open('a.txt','r')

  print(f.read(3))

  2,文件打开方式为b模式时,代表读取三个字节。(读取的不是3的整数倍的时候,不能解码)

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

  print(f.read(6).decode('utf-8'))
  f.seek(0) #将光标移动开头,第0个位置。

  f.seek(3,1) #1代表的含义是相对于当前位置向后读取了三个位置

  f.seek(0,2) #相当于移动从文章最后移动几个位置

#练习,写一个类似于linux 下类似于tail的脚本,总是显示最后一行

import time
import sys
with open(r'%s' % sys.argv[2],'rb') as f:
    f.seek(0,2)

    while True:
        line = f.readline()
        if line:
            print(line.decode('utf-8'),end='')
        else:
            time.sleep(0.2)

truncate:截断文件,只读取部分内容

f.truncate(9)只截取9个字节,剩下的都会被清空

with open('a.txt','r+',encoding='utf-8') as f:
    f.truncate(6)
原文地址:https://www.cnblogs.com/sexiaoshuai/p/7204466.html