檔案的某些操作 以前發過類似的

2022-06-19 11:51:10 字數 2367 閱讀 7095

檔案寫操作

'''

w 寫入操作 如果檔案存在,則清空內容後進行寫入,不存在則建立

a 寫入操作 如果檔案存在,則在檔案內容後追加寫入,不存在則建立

with 使用 with 語句後,系統會自動關閉檔案並處理異常

'''#

import os

#print(os.path)

#from time import

ctime

#使用 w 方式寫入檔案

f = open(r"

test.txt

","w

",encoding = "

utf-8")

print(f.write("

該使用者於 時刻,進行了檔案寫入

".format(ctime())))

f.close()

#使用 a 方式寫入檔案

f = open(r"

text.txt

","a

",encoding = '

utf-8')

print(f.write('

使用 a 方式進行寫入

'.format(ctime())))

f.close()

#使用 with 方式,系統自動關閉檔案並處理異常情況

with open(r

"text.txt

","w

") as f :

'''with方法,對檔案進行關閉並處理異常結果

'''f.write(

''.format(ctime()))

檔案讀操作

import

osdef

mkdir(path):

'''建立資料夾,先看是否存在該檔案,然後再建立

'''#

如果存在,則不進行建立

is_exist =os.path.exists(path)

ifnot

is_exist:

#如果不存在該路徑

os.mkdir(path)

defopen_file(file_name):

'''開啟檔案,並返回讀取到的內容

'''f = open(file_name) #

使用 f 接收檔案物件

f_lst = f.read( ) #

進行讀取檔案

f.close() #

使用完檔案後,關閉

return f_lst #

返回讀取到的內容

獲取字尾名

import

os'''

os.path.splitext('檔案路徑'),獲取字尾名

'''#

將檔案路徑字尾名和前面進行分割,返回型別為元組型別

file_text = os.path.splitext('

./data/py/test.py')

#print(type(file_ext)) #元組型別

front,text =file_text

#front 為元組的第乙個元素

#ext 為元組的第二個元素

print

(front,file_text[0])

#./data/py/test ./data/py/test

print(text,file_text[1])

#.py .py

'''os.path.splitext('檔案路徑')

'''

路徑中的字尾名

import

os'''

使用os.path.split('檔案路徑') 獲取檔名

'''file_text = os.path.split('

./data/py/test.py')

#print(type(file_text))

#元組型別

'''第乙個元素為檔案路徑,第二個引數為檔名

'''path,file_name =file_text

print

(path)

#./data/py

print

(file_name)

#test.py

'''splitext獲取檔案字尾名

'''

2020-05-07

git webStorm不提交某些檔案的一種做法

前提 用webstorm git 進行開發,有一些檔案新增到ignore檔案後,用webstorm的git工具進行提交時仍然能夠看到。考慮新建乙個changelist 如ignore 然後將不想提交的檔案放入此list,通過工具自帶的下拉選進行過濾。一 新建changelist 開啟 9.versi...

VBA刪除某些資料夾下的所有檔案

寫完就發現這個 不用寫得這麼重複的 sub shanchuwenjian dim str as string dim str2 as string 這個vba 是後處理的 載入階段未接觸上進行修正 dim i,jj,kk as integer dim wb as workbook for i 1 t...

DOS命令刪除N天以前的檔案

forfiles p pathname m searchmask s c command d 描述 選擇乙個檔案 或一組檔案 並在那個檔案上 執行乙個命令。這有助於批處理作業。引數列表 p pathname 表示開始搜尋的路徑。預設資料夾是當前工作的目錄 m searchmask 根據搜尋掩碼搜尋檔...