Python基础之shutil模块、random模块

1.shutil模块

  shutil模块是对os模块的功能补充,包含移动、复制、打包、压缩、解压等功能。

1)shutil.copyfileobj()

  复制文件内容到另一个文件,可指定大小内容,如length=16*1024。

1 import shutil
2 f_old = open('old_file','r')
3 f_new = open('new_file','w')
4 shutil.copyfileobj(f_old,f_new,length=16*1024)

2)shutil.copyfile()

  同样将文件内容复制到另一个文件,但是可以直接使用文件名,无须用open()方法打开,事实上此方法调用了shutil.copyfileobj()方法。

1 import shutil
2 shutil.copyfile('f_old','f_new')

3)shutil.copymode()

  每个文件创建时要赋予其一定的权限,比如,只读、可读可写等等,shutil.copymode()方法是将文件的权限复制给另一个文件。

1 import shutil
2 shutil.copymode('f_old','f_new')

4)shutil.copystat()

  将文件所有的状态信息复制至另一个文件,包括权限,组,用户,时间等。

1 import shutil 
2 shutil.copystat('f_old','f_new')

5)shutil.copy()

  将文件的内容和权限复制给另一个文件,相当于先用shutil.copyfile()方法,再用shutil.copymode()方法。

1 import shutil
2 shutil.copy('f_old','f_new')

6)shutil.copy2()

  将文件内容和所有信息状态复制给另一个文件,相当于先用shutil.copyfile()方法,再用shutil.copystat()方法。

1 import shutil
2 shutil.copy2('f_old','f_new')

7)shutil.copytree() 

  可以递归复制多个目录到指定目录下,shutil.copytree(源目录,目标目录,True/False)。

8)shutil.rmtree()

  递归的删除一个目录和目录下的所有文件。

9)shutil.move()

  递归的移动文件,相当于重命名。

10)shutil.make_archive()

  shutil.make_archive(base_name,format,root_dir),压缩,打包文件。

  base_name:压缩包的文件名,也可以是路径,如果是文件名时保存到当前目录,如果是路径时保存至指定路径。

  format:压缩包种类,zip/tar/bztar/gztar。

  root_dir:要压缩的文件夹路径。

  将 F:\\python\\week4 路径下的文件打包放到 当前目录 下,压缩包名字为f_old,压缩方式为zip。

1 import shutil
2 ret = shutil.make_archive("f_old", 'zip', root_dir='F:\\python\\week4')

  将 F:\\python\\week4 路径下的文件打包放到 F:\\python\\week2 路径下,压缩包名字为f_old,压缩方式为zip。

1 import shutil
2 ret = shutil.make_archive("F:\\python\\week2\\f_old", 'zip', root_dir='F:\\python\\week4')

11)ZipFile和TarFile模块

  shutil对压缩包的处理是调用ZipFile和TarFile模块。

2.random模块

  random模块用于生成随机数。

1)random.random()

  random.random()用于生成一个0.0-1.0的随机浮点数。

1 import random  
2 print(random.random())
3 结果:
4 0.7381125452476276

2)random.uniform()

  random.uniform(a,b)用于生成一个指定上下限的随机浮点数,包括上下限值。

1 import random
2 print(random.uniform(1,99))
3 结果:
4 48.088142353356744

3)random.randint()

  random.randint(a,b)用于生成一个指定上下限的随机整型数,包括上下限。

1 import random
2 print(random.randint(1,99))
3 结果:
4 71

4)random.randrange()

  random.randrange()用于生成一个指定上下限的随机整型数,包括左边不包括右边。

1 import random
2 print(random.randrange(1,22))
3 结果:
4 15

5)random.choice()

  random.choice(),从中随机选取一个值。

1 import random
2 print(random.choice([1,2,3,4,5,6]))
3 结果:
4 4

6)random.shuffle()

  rando.shuffle()将一个列表中的元素打乱。

1 import random
2 lis = [1,2,3,4,5,6]
3 random.shuffle(lis)
4 print(lis)
5 结果:
6 [3, 6, 4, 2, 5, 1]

7)random.sample()

  random.sample()从指定序列中随机选取指定长度的字符。

1 import random
2 ret = random.sample('abcdefg',3)
3 print(ret)
4 结果:
5 ['a', 'c', 'f']

猜你喜欢

转载自www.cnblogs.com/foxshu/p/12050032.html