2021-09-08 python基础知识学习:文件操作和os模块
生活随笔
收集整理的這篇文章主要介紹了
2021-09-08 python基础知识学习:文件操作和os模块
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1.文件操作(IO技術(shù))
- (1)打開文件
- (2)編碼
- (3)close()關(guān)閉文件流
- (4)文本文件讀取
- (5)二進(jìn)制文件的讀寫
- (6)文件對(duì)象常用的方法和屬性
- (7)使用pickle序列化
- (8)csv文件的操作
- 2.os和os.path模塊
- (1)os模塊
- (2)文件和目錄操作
- (3)os.path模塊
- (4)walk()遞歸遍歷所有文件和目錄
- (5)shutil拷貝
- (6)壓縮
- 3.遞歸算法
1.文件操作(IO技術(shù))
(1)打開文件
f = open(文件名[,打開方式])
(2)編碼
windows操作系統(tǒng)是GBK,python用Unicode編碼
(3)close()關(guān)閉文件流
s = 'baibaibai' with open('a.txt','w') as f:f.write(s) #或者 try:s = 'baibaibai'f = open('b.txt','w')f.write(s) except BaseException as e:print(e) finally:f.close()(4)文本文件讀取
#讀取前面5個(gè)字符 with open('a.txt','r',encoding='gbk') as f:print(f.read(5))#使用迭代器(每次返回一行)讀取文本文件 with open('a.txt','r',encoding='gbk') as f:for a in f:print(a,end='')#一行一行讀取 with open('a.txt','r',encoding='gbk') as f:while True:fragment = f.readline()if not fragment:breakelse:print(fragment,end='') #把文本文件中的每行都標(biāo)上行號(hào) with open('a.txt','r') as f:lines = f.readlines()lines = [temp.rstrip() + '#'+str(index)+'\n' for index,temp in enumerate(lines)]#推導(dǎo)式生成列表 with open('a.txt','w') as f:f.writelines(lines)#.rstrip() 去掉換行符(5)二進(jìn)制文件的讀寫
不加b,默認(rèn)是文本文件
(6)文件對(duì)象常用的方法和屬性
(7)使用pickle序列化
序列化指將對(duì)象轉(zhuǎn)化成串行化數(shù)字形式
(8)csv文件的操作
# -*- coding: GBK -*- import csv with open('table1.csv','r') as f:a_csv = csv.reader(f) #reader方法print(list(a_csv)) #一個(gè)列表for row in a_csv:print(row) ''' [['id', 'name', 'age', 'salary'], ['1', 'bai', '18', '5000'], ['2', 'selene', '19', '8000'], ['3', 'tutu', '20', '10000']] ''' #后面的循環(huán)不能打印,因?yàn)榍懊鎟eaderh之后,指針到了最后 # -*- coding: GBK -*- import csv with open('table1.csv','r') as f:a_csv = csv.reader(f)for row in a_csv:print(row) ''' ['id', 'name', 'age', 'salary'] ['1', 'bai', '18', '5000'] ['2', 'selene', '19', '8000'] ['3', 'tutu', '20', '10000'] ''' #去掉前面的,就可以打印了 #寫入表格 with open('table2.csv','w') as f:b_csv = csv.writer(f)b_csv.writerow(['id', '姓名', '年齡'])b_csv.writerow(['01', '白', '24'])b_csv.writerow(['02', '白2', '25'])2.os和os.path模塊
(1)os模塊
# -*- coding: GBK -*- import os #os.system('notepad.exe')#調(diào)用記事本程序 #os.system('regedit')#調(diào)用注冊(cè)表 #os.system('cmd')#直接調(diào)用可執(zhí)行的程序(微信) os.system(r'D:\\APP\\weixin\\WeChat\\WeChat.exe')(2)文件和目錄操作
(3)os.path模塊
# -*- coding: GBK -*- import os import os.path print(os.path.isabs('D:/pytorch_learning')) #是否是絕對(duì)路徑,True print(os.path.isdir('D:/pytorch_learning')) #是否是目錄,True print(os.path.isfile('D:/pytorch_learning')) #是否是文件,False print(os.path.exists('D:/pytorch_learning')) #是否存在,Trueprint(os.path.getsize('b.txt')) #字節(jié)大小,131 print(os.path.abspath('b.txt')) #絕對(duì)路徑,D:\pytorch_learning\python051_project\b.txt print(os.path.dirname('D:/pytorch_learning')) #返回目錄的路徑,D:/print(os.path.getctime('b.txt')) #創(chuàng)建的時(shí)間 print(os.path.getatime('b.txt')) #最后訪問(wèn)的時(shí)間 print(os.path.getmtime('b.txt')) #最后修改的時(shí)間path = os.path.abspath('b.txt') print(os.path.split(path)) #分割路徑,返回一個(gè)元組,('D:\\pytorch_learning\\python051_project', 'b.txt') print(os.path.splitext(path)) #返回文件拓展名,按點(diǎn)分割,('D:\\pytorch_learning\\python051_project\\b', '.txt') print(os.path.join('d:\\','python','pytorch')) #連接目錄, d:\python\pytorch # -*- coding: GBK -*- #列出工作目錄下所有的.py文件 import os import os.pathwork_dir = os.getcwd() file_list = os.listdir(work_dir) #獲取所有子目錄 for filename in file_list:if os.path.splitext(filename)[1] == '.py':#或if filename.endwith('py')print(filename) print('##########') file_list2 = [filename for filename in os.listdir(work_dir) if filename.endswith('txt')]#也可以用推導(dǎo)式 for f in file_list2:print(f,end='\n')(4)walk()遞歸遍歷所有文件和目錄
# -*- coding: GBK -*- import os path = os.getcwd() print(path) file_list = os.walk(path) for dirpath,dirnames,filenames in file_list:for dir in dirpath:print(dir)(5)shutil拷貝
# -*- coding: GBK -*- import shutil shutil.copyfile('a.txt','a_copy.txt') #拷貝文件 shutil.copytree('movie','movie2') #拷貝文件夾 shutil.copytree('movie','movie3',ignore=shutil.ignore_patterns('*.txt','*.zip')) #拷貝文件夾,.txt和.zip的都不考(6)壓縮
shutil.make_archive()
zipfile
3.遞歸算法
#階乘 def factorial(i):global aa = a * ii = i-1if i >1:factorial(i)else:print(a) ######更簡(jiǎn)單的寫法######## factorial(int(input('input one number:')))def factorial2(i):if i == 1:return ielse:return i*factorial2(i-1)print(factorial2(5)) # -*- coding: GBK -*- #遞歸打印所有目錄和文件 import os def getAllFiles(path):childFiles = os.listdir(path)for file in childFiles:filepath = os.path.join(path,file)if os.path.isdir(filepath):getAllFiles(filepath)print(filepath) getAllFiles('movie') '''結(jié)果 movie\a.txt movie\America\bigbang movie\America movie\gg.zip movie\Korae '''總結(jié)
以上是生活随笔為你收集整理的2021-09-08 python基础知识学习:文件操作和os模块的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 想要减少广告浪费,你需要学会这些设计常识
- 下一篇: websocket python爬虫_p