Python 3ファイル(osライブラリ)でよく使われるシーンと使い方
3428 ワード
2020年11月下旬に整理し、平凡に甘んじないあなたにもっとpython 3の基礎知識を捧げます.https://blog.csdn.net/weixin_45316122/article/details/109843899
Trick:純demo、心はどこにあるのか、結果はそこにある.
import os
"""
1.
'a.txt'
1)
os.rename('abc.txt','a123.txt')
>>'abc.txt' 'a123.txt'
2)
os.remove('a123.txt')
, 'a123.txt'
:
if os.path.exists('a123.txt'):
os.remove('a123.txt')
2.
path='/users/Python/Data/info.txt'
1)
print os.path.dirname(path)
>>/users/Python/Data
2)
print os.path.basename(path)
>>info.txt
3)
print os.path.split(path)
>>('/users/Python/Data', 'info.txt')
3.
test01,test02
1)
os.mkdir('test01')# test01
os.mkdir('test02')# test02
, ,
if not os.path.exists('test01'):
os.mkdir('test01')
if not os.path.exists('test02'):
os.mkdir('test02')
2)
|---test01--------
|---test02--------
|---demo_file.py--
print os.listdir('.')
>>['demo_file.py', 'test01', 'test02']
test01 , ,
print list(os.walk('.'))#walk()
>>[('.', ['test01', 'test02'], ['demo_file.py']), ('.\\test01', [], []), ('.\\test02', [], [])]
3)
print os.getcwd()
>>C:\Users\xx\Python\Test
4)
os.rmdir('test02')
>> test02
test02 , , . shutil ,
4.
, , .
python , :
|---test01--------
|---test02--------
|---demo_file.py--
1)
print os.path.isfile('test01')
>>False
print os.path.isfile('demo_file.py')
>>True
2)
print os.path.isdir('test01')
>>True
3) link
linux link
print os.path.islink('link_file')
4)
, , :
print os.path.exists('demo_file.py')
>>True
print os.path.exists('test01')
>>True
"""
# a = {}.fromkeys(("aa","bb","cc"),100)
# # for k,v in a.items():
# # print(k,v)
#
#
# # , ,
# # d ={1:'a',2:'b',3:"c"}
# # print(d.get(4,"xx"))
# # print(d.get(3,"xx"))
#
#
# #
# # aInfo={'Wangdachui':3000,'NiuYun':2000,'LinLing':4500,'Tianqi':8000}
# # template='''
# # Welcome to the pay wall.
# # NiuYun' salary is %(NiuYun)s.
# # Wangdachui's salary is %(Wangdachui)s.
# # '''
# # print(template%aInfo )
#
# # , _
# # def g():
# # return 'class room is 203',1000,'2016-10-06'
# # _,price,_=g()
# # print(price)
#
#
# # , None
# # def divide(a,b):
# # try:
# # return True,a/b
# # except ZeroDivisionError:
# # return False,None
#
# print (divide(0,10))
import time,datetime
#
# def f(message,when = None):
# when = datetime.datetime.now()
# print('%s:%s'%(when,message))
#
# f("hi xiaohonghong")
# time.sleep(1)
# f("hi xiaohonghong again")