python bytes查找位置_Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块
StringIO
StringIO操作
BytesIO
BytesIO操作
file-like對象
路徑操作
路徑操作模塊
3.4版本之前:os.path模塊
3.4版本開始
建議使用pathlib模塊,提供Path對象來操作。包括目錄和文件
pathlib模塊
from pathlib import Path
目錄操作
初始化
路徑拼接和分解
#在windows下的Pycharm中運行
p =Path()print(type(p)) #
p = p / 'a'
print(p) #a
p1 = 'b' /pprint(p1) #b\a
p2 = Path('c')
p3= p2 /p1print(p3) #c\b\a
print(p3.parts) #('c', 'b', 'a')
print(p3.joinpath('etc','init.d',Path('httpd'))) #c\b\a\etc\init.d\httpd
p = Path('/etc')print(str(p),bytes(p))
p = Path('/a/b/c/d')print(p.parent.parent)for x inp.parents:print(x)
#四個屬性,兩個方法
p = Path('E:\learnshare\ArticleSpider\e.xex.txt')print(p.name) #e.xex.txtprint(p.stem) #e.xexprint(p.suffix) #.txtprint(p.suffixes) #['.xex','.txt']print(p.with_name('c.y'))#E:\learnshare\ArticleSpider\c.yprint(p.with_suffix('.xxyy'))#E:\learnshare\ArticleSpider\e.xex.xxyy
調用iterdir()方法后返回一個生成器對象
通配符
glob(pattern)通配給定的模式
rglob(pattern)通配給定的模式,遞歸目錄
from pathlib importPathprint(1,list(Path().glob('test*')))#返回當前目錄對象下的test開頭的文件
print(2,list(Path().glob('*/test*')))#返回當前目錄的下一級目錄以test開頭的文件
print(3,list(Path().glob('**/test*')))#遞歸當前目錄以及其下所有目錄,返回以test開頭的文件
print(4,list(Path().rglob('test*')))#同上一樣
匹配
match(pattern)
模式匹配,成功返回True
文件操作
OS模塊
fd表示文件描述符
shutil模塊
到目前為止
文件拷貝:使用打開2個文件對象,源文件讀取內容,寫入目標文件中來完成拷貝過程。但是這樣會丟失stat數據信息(權限等),因為根本就沒有復制過去。
目錄怎么辦呢?
Python提供了一個方便的庫shutil(高級文件操作)
Copy復制
importshutil
with open('test1.txt','r+') as f1:
f1.write('abcd\n1234')
f1.flush()
with open('test2.txt','w+')as f2:
shutil.copyfileobj(f1,f2)#注意:由于指針的緣故,可參見源碼如下。上述代碼中abcd\n1234內容確實會寫入到test1.txt,但是并沒有復制到test2.txt中。
#copyfileobj源碼
def copyfileobj(fsrc, fdst, length=16*1024):"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf=fsrc.read(length)if notbuf:breakfdst.write(buf)
#copytree源碼,這里主要了解一下ignore函數的使用技巧,過濾掉不需要拷貝的!
def copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2,
names=os.listdir(src)if ignore is notNone:
ignored_names=ignore(src, names)else:
ignored_names=set()
os.makedirs(dst)
errors=[]for name innames:if name inignored_names:continuesrcname=os.path.join(src, name)
dstname=os.path.join(dst, name)
...return dst
deffn(src,file_names):
filter(lambda x:x.startwith('t'),file_names)#上面的語句等同于下面的語句
fn = lambda src,names:filter(lambda x:x.startwith('t').file_names)#filter(function, iterable)#注意: Pyhton2.7 返回列表,Python3.x 返回迭代器對象
#假設D:/temp下有a,b目錄
defignore(src,names):
ig= filter(lambda x:x.startwith('a'),names) #忽略a
returnset(ig)
shutil.copytree('o:/temp','o:/tt/o',ignore=ignore)
rm刪除
shutil.rmtree('D:/tmp') #類似rm -rf
move移動
#在同一盤符下,其實質上就是rename,跨盤符的話才是真正的移動
os.rename('D:/temp/x.txt','D:/t.txt')
os.rename('test3','/tmp/py/test')
csv文件
csv文件簡介(文本格式,半結構化數據)
手動生成CSV文件
from pathlib importPath
p= Path('F:\\百度網盤下載資料\\Python全棧開發\\python進階1\\19Python的文件IO(三)(6)\\test.csv')
parent=p.parentif notparent.exists():
parent.mkdir(parents=True)
csv_body= '''\
id,name,age,comment
1,zs,18,"I'm 18"
2,ls,20,"This is a testing"
3,ww,232,"中
國"'''p.write_text(csv_body)
csv模塊
from pathlib importPathimportcsv
p= Path('F:\\test.csv')
with open(str(p)) as f:
reader=csv.reader(f)print(next(reader))
row= [4,'cty',22,'tom']
rows=[
(1,'2',3,'55'),
(11,'123',22,"\"123123")
]
with open(str(p),'a+') as f:
writer=csv.writer(f)
writer.writerow(row)
writer.writerows(rows)
ini文件
作為配置文件,ini文件格式很流行
中括號里面的部分稱為section。
每一個section內,都是key=value形成的鍵值對,key稱為option選項。
configparser
from configparser importConfigParser
cfg=ConfigParser()
cfg.read('mysql.ini')print(cfg.sections())print(cfg.has_section('deploy'))print(cfg.items('deploy'))for k,v in cfg.items('deploy'):print(k,type(v))
tmp= cfg.get('deploy','a')print(tmp,type(tmp))print(cfg.get('deploy','a',fallback='python'))print(cfg.getint('mysql','aa'))if cfg.has_section('mysql'):
cfg.remove_section('mysql')
cfg.add_section('cy')
cfg.set('cy','ly','5')
cfg.set('cy','ggz','2')#上面的刪除和新增功能需要重新寫入文件才會生效
with open('mysql.ini','w') as f:
cfg.write(f)print(cfg.getint('cy','ggz'))print(cfg.remove_option('cy','ly'))
with open('mysql.ini','w') as f:
cfg.write(f)
注意:配置文件一般加載后常駐于內存中,且讀取操作遠遠多于寫入操作。
總結
以上是生活随笔為你收集整理的python bytes查找位置_Python进阶5---StringIO和BytesIO、路径操作、OS模块、shutil模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [云炬创业学笔记]第二章决定成为创业者测
- 下一篇: [云炬创业学笔记]第二章决定成为创业者测