Python自动化学习笔记(四)——Python数据类型(集合set,元组tuple)、修改文件、函数、random常用方法

1.修改文件的两种方式

1 #第一种
2 with open('users','a+') as fw:  #用a+模式打开文件,使用with这种语法可以防止忘记close文件
3     fw.seek(0)  #移动文件指针到最前面,然后才能读到内容
4     result=fw.read()    #将文件内容一次性读取出来
5     new_result =result.replace('BAC','python')      #字符串替代
6     fw.seek(0)      #移动文件指针到最前面
7     fw.truncate()  #清空文件内容
8     fw.write(new_result)    #字符串替代后的所有内容一次性写入文件
1 #第二种
2 import os   #导入os模块
3 with open('users') as fr,open('.users','w',encoding='utf-8')as fw:  #r模式打开待修改文件,w模式打开一个新文件
4     for line in fr: #直接循环文件对象,每次取的就是文件里的每一行
5         new_line=line.replace('java','修改文件')    #一行一行替换字符串
6         fw.write(new_line)      #一行一行写入新文件
7 os.remove('users')      #删除原文件
8 os.rename('.users','users')     #将新文件修改为原文件的名字

 2.Python数据类型(集合set,元组tuple)

2.1元组

可以将元组看作是只能读取数据不能修改数据的list

2.1.1定义一个空的元组

  • a=()
  • a=tuple()

2.1.2定义只有一个元素的元组

  • a=(1,) #定义元组的时候,只有一个元素,后面必须加逗号

2.2集合

#集合天生去重复,无序

2.2.1定义一个空的集合

  • a=set()  #不能使用{}来定义,{}是定义一个空字典

2.2.2集合常用方法

 1 stus1 = {'胡绍燕','王义','王新','马春波','高文平'}
 2 
 3 stus2 = {'乔美玲','胡绍燕','王义','王新','马春波',"王一铭"}
 4 
 5 #交集,两个集合中都有的
 6 res1=stus1.intersection(stus2)
 7 res2=stus1&stus2
 8 
 9 
10 #并集,合并两个集合,并去重
11 res1=stus1.union(stus2)
12 res2=stus1|stus2
13 
14 
15 #差集,前一个有,后面一个没有的
16 res1=stus1.difference(stus2)
17 res2=stus1-stus2
18 
19 
20 #对称差集,只在一个集合中出现的元素组成的集合
21 res1=stus1.symmetric_difference(stus2)
22 res2=stus1^stus2
23 
24 
25 stus1.add('abc')     #增加元素
26 stus1.pop()   #随机删除元素,返回删除的元素
27 stus1.remove('abc') #删除指定元素
28 for s in stus1:     #遍历
29     print(s)
1 l=[1,2,3,4,2,3]
2 lset=set(l)  #将list转为set,自动去重
3 print(lset)

2.2.3常量集合

import string
print(string.ascii_lowercase)  #小写字母
print(string.ascii_uppercase)   #大写字母
print(string.digits)     #0-9
print(string.ascii_letters)   #字母
print(string.punctuation)   #特殊符号

3.函数

 1 def hello():    #定义函数
 2     print('hello')
 3 hello() #调用函数
 4 
 5 #有传参无返回的函数
 6 def write_file(file_name,content):   #形参
 7     print(file_name,content)
 8     with open(file_name,'a+',encoding='utf-8') as fw:
 9         fw.writelines(content)
10 write_file('a.txt','123\n')   #实参
11 
12 #有传参有返回的函数
13 def read_file(file_name):   #形参
14     print(file_name)
15     with open(file_name,'a+',encoding='utf-8') as fw:
16         fw.seek(0)
17         content=fw.read()
18         return content      #返回一个变量
19 res=read_file('users')
20 print(res)

4.random常用方法

  • random.randint(1,20) #随机获取并返回一个指定范围的整数
  • random.choice(s) #随机选择一个元素返回,s='xfdfdfdfd'
  • random.sample(s,3) #随机选择几个元素返回
  • random.shuffle(l) #只能传入一个list,打乱顺序,返回是None,l=[1,2,3,4]
  • random.uniform(1,2) #随机获取并返回一个指定范围内的小数,round(f,3) #小数点后保留几位



猜你喜欢

转载自www.cnblogs.com/luoyc/p/10018510.html