記錄在我使用python程序中用到的檔案操作,我使用python主要是用來解決自動化的問題,不僅僅是作業上的問題也有解決我自己自動化的工具,python是可以跨平臺的而bat腳本只能在windows上跑
路徑轉義符
對于路徑中含有轉義字符,在路徑字串前加 r,比如 filepath = r'E:\Code\test.txt'
從相對路徑或含../的路徑獲取完整路徑: os.path.abspath(xxx)
文本讀取和修改
使用默認的系統函式 open,并添加encoding,使用with 代替try finally 切保一定會呼叫close釋放檔案,示例
with open(test_blog,'r',-1,encoding="utf-8") as sw:
逐行讀取并替換內容
def alter(file,old_str,new_str):
"""
替換檔案中的字串
:param file:檔案名
:param old_str:就字串
:param new_str:新字串
:return:
"""
file_datahttps://www.cnblogs.com/zhaoqingqing/archive/2021/06/13/= ""
with open(file, "r", encoding="utf-8") as f:
for line in f:
if old_str in line:
line = line.replace(old_str,new_str)
file_data += line
with open(file,"w",encoding="utf-8") as f:
f.write(file_data)
alter("file1", "09876", "python")
寫入內容
# 打開一個檔案
fo = open("foo.txt", "w")
fo.write( "www.runoob.com!\nVery good site!\n")
# 關閉打開的檔案
fo.close()
參考: python-修改檔案內容并保存的3種方法
檔案和目錄操作
創建檔案夾:os.mkdir
檔案拷貝:shutil.copyfile(src_fullpath, path_name)
洗掉檔案:os.remove(file_name)
python呼叫資源管理器打開某個檔案夾:os.startfile(full_path)
進入某個目錄,此后的操作是在這個目錄下:os.chdir(full_path)
檔案夾拷貝
如果目錄存在需要先洗掉,否則會報目錄不為空不可訪問
if os.path.exists(dst_path):
print("exist path,delete", dst_path)
shutil.rmtree(dst_path)
shutil.copytree(src_path, dst_path)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/287056.html
標籤:其他
下一篇:Spring試錯筆記(一)
