Python字串操作 批量修改檔名

2021-08-20 05:05:00 字數 1055 閱讀 1696

一 字串擷取

lines = lines[3:]
捨去前兩個字元

二 字串的替換

refile = lines.replace(',', ' ')
將,替換為空格

三 應用

def delete():

file = open("iris.txt",'w')

file2 = open("iris_new.txt")

for lines in file2:

#lines = lines[3:]

refile = lines.replace(',', ' ') # 替換,

#refile1 = refile.replace('\n', '') # 替換換行符

file.write(refile)

print(refile)

file.close()

file2.close()

四 批量修改檔名

import os

def rename():

count=加入的數字;

path='原始檔案路徑'

filelist=os.listdir(path)#該資料夾下所有的檔案(包括資料夾)

for files in filelist:#遍歷所有檔案

olddir=os.path.join(path,files);#原來的檔案路徑

filename=os.path.splitext(files)[0];#檔名

filetype=os.path.splitext(files)[1];#副檔名

newdir=os.path.join(path,str(count)+ '-' +filename + filetype);#新的檔案路徑

os.rename(olddir,newdir);#重新命名

count+=1;

rename();

效果:

原始:修改後:

python 修改字串

在python中,字串是不可變型別,即無法直接修改字串的某一位字元。因此改變乙個字串的元素需要新建乙個新的字串。常見的修改方法有以下4種。方法1 將字串轉換成列表後修改值,然後用join組成新字串 s abcdef 原字串 s1 list s 將字串轉換為列表 s1 a b c d e f 列表的每...

Python字串操作

1 複製字串 str2 str1 2 鏈結字串 str abc 3 查詢字串 string.find sub string.index sub string.rfind sub string,rindex sub 4 字串比較 cmp str1,str2 cmp str1.upper str2.up...

Python字串操作

python如何判斷乙個字串只包含數字字元 python 字串比較 下面列出了常用的python實現的字串操作 strcpy sstr1,sstr2 sstr1 strcpy sstr2 sstr1 sstr1 strcpy2 print sstr2 strcat sstr1,sstr2 sstr1...