python中的常用方法

时间:2021-06-24 14:29:21

1.os模块的常用方法:

>>> import os
>>>
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx'] # 组合目录路径
>>> for filename in myFiles:
print(os.path.join('C:\\Users\\sxhui101', filename)) C:\Users\sxhui101\accounts.txt
C:\Users\sxhui101\details.csv
C:\Users\sxhui101\invite.docx >>> os.getcwd() # 获取当前工作目录
'C:\\Python\\Python35' >>> os.chdir('D:\\mzitu') # 更改当前工作目录
>>> os.getcwd()
'D:\\mzitu' >>> os.makedirs('D:\\mzitu\\beauty') # 创建目录

2.enumerate用法:

for i, j in enumerate[a, b, c]:
print(i, j, sep=" ") # 0 a
# 1 b
# 2 c

3.for循环与while循环

for i in range(10):  # for循环
  if i == 5: # 可以将5变成11试试,可以发现如果是5,不会打印done;如果是11则会打印done
break # 跳出整个循环,只会打印前5个数字;换成continue,跳出本循环,进行下一个循环,就不会打印5了
  print(i)  
else: 
  print("done")
count = 0
while count < 10: # while循环
print(count)
count += 1
else:
print("you have counted for ten times!")

4.格式化输出

name = "Shuai xianghui"
age = 1
address = "Hang Zhou" info1 = '''
---------- info of %s --------------
Name: %s
Age: %d
Address: %s
''' % (name, name, age, address) info2 = '''
---------- info of {_name} --------------
Name: {_name}
Age: {_age}
Address: {_address}
'''.format(_name=name, _age=age, _address=address)