基于Python語言的文件與文件夾管理
第1關(guān) 創(chuàng)建子文件夾
import os
def mkDir():
# 創(chuàng)建名為 'dst' 的文件夾
os.makedirs('dst', exist_ok=True)
# 如果文件被直接運(yùn)行,執(zhí)行測試代碼
if __name__ == "__main__":
mkDir()
# 判斷當(dāng)前文件夾中是否存在文件夾 'dst'
if os.path.exists('dst') and os.path.isdir('dst'):
print('mkdir success')
else:
print('dst does not exist')
第2關(guān) 刪除帶有只讀屬性的文件
import os
import sys
def removeFile():
# 刪除 'src/removeme.txt' 文件
try:
os.remove('src/removeme.txt')
print('remove success')
except FileNotFoundError:
print('remove success')
sys.exit()
# 如果文件被直接運(yùn)行,執(zhí)行測試代碼
if __name__ == "__main__":
removeFile()
第3關(guān) 批量復(fù)制文件夾中的所有文件
未通過本題,如果您通過了本題歡迎補(bǔ)充到評論區(qū),有時(shí)間我會整理進(jìn)來文章來源地址http://www.zghlxwxcb.cn/news/detail-823741.html
文件處理
第1關(guān) 讀取宋詞文件,根據(jù)詞人建立多個(gè)文件
import shutil
import os
if os.path.exists("wjcl/src/step3/cr"):
shutil.rmtree("wjcl/src/step3/cr")
os.mkdir("wjcl/src/step3/cr")
f1=open("wjcl/src/step1/宋詞.txt",'r')
#代碼開始
#os.chdir("wjcl/src/step3/cr")
for line in f1.readlines():#逐行讀取文件
k=0
if " "in line:
k=1
pos=line.find(" ")#pos為冒號所在位置
pos1=line.find("\n")
xm=line[pos+1:pos1]#截取姓名
if xm !="": f2=open('wjcl/src/step3/cr/'+xm+".txt",'a+')#以追加的方式打開文件xm.txt(不存在就新建,存在就打開)
if len(line.strip("\n").strip())>0:
f2.write(line)#將讀出的內(nèi)容寫入文件
if len(line.strip("\n").strip()) > 0 and k !=1:
f2.write(line) # 將讀出的內(nèi)容寫入文件
#代碼結(jié)束
f1.close()
f2.close()
第2關(guān) 讀取宋詞文件,并根據(jù)詞人建立多個(gè)文件夾
import os
import shutil
if os.path.exists("wjcl/src/step4/sccr"):
shutil.rmtree("wjcl/src/step4/sccr")
os.mkdir("wjcl/src/step4/sccr")
f1=open("wjcl/src/step1/宋詞.txt",'r')
#代碼開始
for line in f1.readlines():#逐行讀取文件
k=0
if " "in line:
k=1
pos=line.find(" ")#pos為冒號所在位置
pos1=line.find("\n")
xm=line[pos+1:pos1]#截取姓名
if not os.path.exists("wjcl/src/step4/sccr/"+xm):os.mkdir("wjcl/src/step4/sccr/"+xm)#以追加的方式打開文件xm.txt(不存在就新建,存在就打開)
f1.close()
#代碼結(jié)束
第3關(guān) 讀取宋詞文件,建立多個(gè)詞人文件夾,為每首詞在文件夾下建立文本文件
import os
import shutil
if os.path.exists("wjcl/src/step5/cr"):
shutil.rmtree("wjcl/src/step5/cr")
os.mkdir("wjcl/src/step5/cr")
f1=open("wjcl/src/step1/宋詞.txt",'r')
#代碼開始
list_str = f1.readlines()
temp_str = ''
name = ''
for s in list_str:
if s.find(' ') != -1:
if len(temp_str) == 0:
temp_str += s
else:
if name == '':
name = s
file_path = 'wjcl/src/step5/cr/' + name[name.find(' ') + 1:-1]
if not os.path.exists(file_path):
os.mkdir(file_path)
title_path = file_path + '/' + name[0:name.find(' ')] + '.txt'
f2 = open(title_path, 'a+', encoding='utf-8')
f2.write(temp_str)
f2.close()
temp_str = s
name = s
else:
temp_str += s
file_path = 'wjcl/src/step5/cr/' + name[name.find(' ') + 1:-1]
if not os.path.exists(file_path):
os.mkdir(file_path)
title_path = file_path + '/' + name[0:name.find(' ')] + '.txt'
f2 = open(title_path, 'a+', encoding='utf-8')
f2.write(temp_str)
f2.close()
f1.close()
#代碼結(jié)束
第4關(guān) 文件的統(tǒng)計(jì)
import os
wjzd={}
wjsize={}
lj="wjcl/src/test"
#代碼開始
def get_size_type(f_path):
global lj
files_name = os.listdir(f_path)
for name in files_name:
file_path = os.path.join(f_path, name)
ty = str(os.path.splitext(file_path)[1]).strip('.')
if os.path.isdir(file_path):
get_size_type(file_path)
if not ty or ty == 'gitkeep':
continue
else:
wjzd.setdefault(ty, 0)
wjzd[ty] += 1
wjsize.setdefault(ty, 0)
wjsize[ty] += os.path.getsize(file_path)
get_size_type(lj)
ans = ['txt', 'mp3', 'jpg', 'pptx']
#代碼結(jié)束
for x in ans:
print("文件類型{}文件數(shù){}文件大小{:.2f}KB".format(x,wjzd[x],wjsize[x]/1024))
第5關(guān) 文件的移動
import os
import shutil
wj={"圖片":".jpeg.jpg.png.jfif","文檔":".txt.docx.pdf","音樂":".mp3.wav","影像":".mp4.flv"}
lj1="wjcl/src/test2"
lj="wjcl/src/test3"
if os.path.exists(lj):
shutil.rmtree(lj)
shutil.copytree(lj1,lj)
#代碼開始
def move_file(path):
if not os.path.exists(lj + path):
os.mkdir(lj + path)
shutil.move(file_path, lj + path)
files = os.listdir(lj)
for name in files:
file_path = os.path.join(lj, name)
ty = str(os.path.splitext(name)[1])
if ty == '.gitkeep' or name == '.gitkeep':
continue
if wj['圖片'].find(ty) != -1:
move_file('/img')
elif wj['文檔'].find(ty) != -1:
move_file('/idoc')
elif wj['音樂'].find(ty) != -1:
move_file('/music')
elif wj['影像'].find(ty) != -1:
move_file('/video')
#代碼結(jié)束
#for x in os.listdir(lj):
# if x!=".gitkeep":
# print(os.listdir(lj+"/"+x))
l = [['青城山.png', '杜甫草堂.png', '春熙路圖集3.jfif', 'ifs大熊貓.jpg', '春熙路圖集2.jpeg', '基地1.jpg', '春熙路圖集1.jfif'],
['學(xué)院設(shè)置.docx', '昆明.docx', '考題四.pdf', '琵琶行并序.txt', '考題一.pdf'],
['pq.flv', '七彩丹霞視頻.mp4', '云南十八怪_.mp4'],
['花兒尕戀手令.mp3', 'add.wav', 'score.wav', '山歌好比春江水.mp3']]
for n in l:
print(n)
#代碼結(jié)束
利用csv模塊進(jìn)行csv文件的讀寫操作
第1關(guān) csv文件的讀操作
import csv #導(dǎo)入csv模塊
########## Begin ##########
contents=[]
filename='project/iris.csv'
csv_file=open(filename,mode='r',encoding='utf-8')
reader=csv.reader(csv_file)
for item in reader:
contents.append(item) #打開數(shù)據(jù)集的文件,file是相應(yīng)的文件句柄
#讀取數(shù)據(jù),把數(shù)據(jù)放在contents中
########## End ##########
for line in contents: #打印文件內(nèi)容
########## Begin ##########
print(line)
########## End ##########
line_num=len(contents)
print(line_num)
第2關(guān) csv文件的寫操作
import csv
########## Begin ##########
filename='project/students.csv'
csvfile2=open(filename,'w',newline='')
writer2=csv.writer(csvfile2) #打開文件,newline是否換行的參數(shù)
#如果不指定newline='',則每寫入一行將有一空行被寫入
########## End ##########
row=["序號","學(xué)號","姓名","性別","學(xué)院"]
rows=[[1,"1409090312","張雨","女","計(jì)算機(jī)學(xué)院"],
[2,"1409103265","陳敢","男","理學(xué)院"],
[3,"1509111023","李家祥","女","計(jì)算機(jī)學(xué)院"],
[4,"1409090311","鄧貴","男","理學(xué)院"],
]
########## Begin ##########
writer2.writerow(row)
writer2.writerows(rows)
row1=['1',"1409090312","張雨","女","計(jì)算機(jī)學(xué)院"]
row2=['2',"1409103265","陳敢","男","理學(xué)院"]
row3= ['3',"1509111023","李家祥","女","計(jì)算機(jī)學(xué)院"]
row4=['4',"1409090311","鄧貴","男","理學(xué)院"] #將row和rows寫入文件
print(row)
print(row1)
print(row2)
print(row3)
print(row4,end='')
# for item in rows
# print(item)
# filename='project/students.csv'
# with open(filename,'r')as file:
# csv_reader=csv.reader(file)
# for row in csv_reader:
# print(row)
########## End ##########
文章來源:http://www.zghlxwxcb.cn/news/detail-823741.html
到了這里,關(guān)于【頭歌】——數(shù)據(jù)分析與實(shí)踐-基于Python語言的文件與文件夾管理-文本 文件處理-利用csv模塊進(jìn)行csv文件的讀寫操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!