Python之檔案操作例項 批量修改檔案的字首名

2021-10-01 19:29:49 字數 1208 閱讀 2473

# 匯入包,很重要的

import os

"""# 建立資料夾及檔案

os.mkdir("./test")

for i in range(1, 6):

os.mkdir("./test/test"+str(i))

fp = open("./test/test"+str(i)+".txt", 'w',encoding='utf-8')

"""while

true

:print

("功能**:\n1.新增字首\t2.刪除字首"

) sn =

input

("請選擇您的操作**:"

) profix =

input

("請輸入字首:"

) path =

input

("請輸入您的檔案路徑:"

)# 獲取路徑下的所有資料夾及檔案

file_list = os.listdir(path)

# print(file_list)

# 遍歷所有的檔案

for i in file_list:

path_flag = os.path.isfile(os.path.join(path, i))if

not path_flag:

# 跳過目錄

continue

# 判斷執行的操作.並對非目錄的檔案進行操作

if sn ==

'1':

# pass # 新增字首

os.rename(os.path.join(path, i)

, os.path.join(path, profix + i)

)# os.path.join(path, profix + i) 連線路徑

elif sn ==

'2':

# pass # 刪除字首

if i.startswith(profix)

: os.rename(os.path.join(path, i)

, os.path.join(path, i[

len(profix):]

))else

:print

("執行**錯誤!!!"

)else

:print

("執行成功!!"

)

shell 例項之檔案操作

bin bash 建立檔案 if d testdir then mkdir testdir ficd testdir if f test.lua.bak.2017 then touch test.lua.bak.2017 fiif d subdir then mkdir subdir cd subd...

原創 Python批量操作檔案,批量合併

最近幾個小夥伴在手動合併一些文字檔案,感覺可以用python批量實現,就有了這段 1 importos2 importre3 import sys4 5def printenter f1 每兩個檔案之間的換行操作 6 f1.write n n n 7for i in range 23 8 f1.wr...

Python之批量建立檔案

批量建立檔案其實很簡單,只需要按照需要建立寫檔案 寫完關閉當前寫檔案 建立新的寫檔案 寫完關閉當前檔案 不斷迴圈即可,以下是乙個簡單例子,將大檔案big.txt按照每1000行分割成乙個個小檔案,具體做法如下 coding utf 8 index 0 count 0 f in open d.txt ...