python創(chuàng)建文件備份的腳本
制作文件備份
打開(kāi)原文件
old_f_name = input(“請(qǐng)輸入備份的文件路徑:”) old_f = open(old_f_name, “r”)
打開(kāi)新文件
new_f_name = “[復(fù)件]” + old_f_name 123.txt -> 123[復(fù)件].txt 123 + “[復(fù)件]” + .txt index = old_f_name.rfind(“.”) # 獲取.對(duì)應(yīng)的后綴 if index >= 0: # 如果有后綴 new_f_name = old_f_name[:index] + “[復(fù)件]” + old_f_name[index:] else: # 如果沒(méi)有后綴 new_f_name = old_f_name + “[復(fù)件]” new_f = open(new_f_name, “w”)
讀取原文件內(nèi)容
content = old_f.read()
寫(xiě)入到新文件中
new_f.write(content)
關(guān)閉原文件
old_f.close()
關(guān)閉新文件
new_f.close()
補(bǔ)充:下面看下python文件備份腳本
import os
import time
source = ['D:\\MyDrivers\hotfix'] #這里可以用自然字符串表示r',因?yàn)閣indows下的分隔符
與python的有沖突,所以需要轉(zhuǎn)義字符\
# 2. 備份文件到目標(biāo)路徑
target_dir = 'F:\\DMDownLoad\\' #這里的末尾一定不要丟分隔符,否者創(chuàng)建的文件會(huì)在F:目錄下,
而不會(huì)在DMDownload目錄下
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d') #time.strftime表示對(duì)當(dāng)前時(shí)間的調(diào)用,括號(hào)內(nèi)為參數(shù)設(shè)定
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment -->')
if len(comment)==0:
target = today+os.sep+now+'.zip'
#os.sep表示目錄符號(hào),windows下是\\,linux下是/,mac下是:,這里為了保證移植性,
所以os.sep會(huì)根據(jù)系統(tǒng)給出分隔符
else:
target = today+os.sep+now+'_'+\
comment.replace(' ','_')+'.zip'
# Notice the backslash!
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print('Successfully created directory', today)
# 5. 用winrar的rar命令壓縮文件,但首先要安裝有winrar且設(shè)置winrar到環(huán)境變量的路徑path中
zip_command = "rar a %s %s" %(target,''.join(source))
#這行命令之前的所有target 、target_dir、today這些都是字符串,只有在
這個(gè)命令和os.makedir中才是真正的表示路徑
# Run the backup
#設(shè)置winrar到path環(huán)境中,這里已經(jīng)手動(dòng)添加了,如果沒(méi)有去掉#號(hào)
#os.system('set Path=%Path%;C:\Program Files\WinRAR')
if os.system(zip_command)==0:
print'Successful backup to', target
else:
print'Backup FAILED'
總結(jié)
以上所述是小編給大家介紹的python創(chuàng)建文件備份的腳本,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
python實(shí)現(xiàn)不同文件夾下的函數(shù)相互調(diào)用
這篇文章主要介紹了python實(shí)現(xiàn)不同文件夾下的函數(shù)相互調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
python正則爬取某段子網(wǎng)站前20頁(yè)段子(request庫(kù))過(guò)程解析
這篇文章主要介紹了python正則爬取某段子網(wǎng)站前20頁(yè)段子(request庫(kù))過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
關(guān)于Python函數(shù)的定義和參數(shù)
這篇文章主要介紹了關(guān)于Python函數(shù)的定義和參數(shù),Python中的函數(shù)我們可以理解成是一種具有功能的包裝塊,也就是封裝具有某一種功能的代碼塊,需要的朋友可以參考下2023-04-04
python3+PyQt5 自定義窗口部件--使用窗口部件樣式表的方法
今天小編就為大家分享一篇python3+PyQt5 自定義窗口部件--使用窗口部件樣式表的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06

