Python里面路徑操作
一般情況下,我們可以使用os創(chuàng)建文件目錄,使用shutil移動和復(fù)制文件
import os
import shutil
獲取信息
os.getcwd() #獲取當(dāng)前目錄
os.listdir() #以列表形式獲取目錄下所有工作目錄
os.walk() #返回一個生成器,該生成器包含當(dāng)前目錄和所有子目錄的文件名稱及路徑信息
aa=os.walk(os.getcwd())
for dir_path, dir_names, file_names in aa:
for f in file_names:
print(f)
更改信息
os.chdir() #更改當(dāng)前工作路徑
os.path.join() #創(chuàng)建路徑供后續(xù)使用
os.makedirs() #創(chuàng)建目錄
os.remove() #刪除文件
os.path.isfile() #判斷文件是否存在(只能判斷單個文件)
os.path.exists() #判斷文件或文件夾是否存在()
shutil.copy2('source_file_path', 'destination_file_path') #復(fù)制文件或文件夾
shutil.move('source_file_path', 'destination_file_path') #移動文件或文件夾
shutill.rmtree('my_directiory_path') #刪除路徑以及包含的所有文件夾和文件
Python里面讀取數(shù)據(jù)
打開文件
open(filename, 'r+')
讀取內(nèi)容
f.readlines() #一次性全部讀取
f.readline() #一行一行讀取
判斷每行內(nèi)容,選擇是否忽略
if line.startswith('#') or line.strip() == '';
continue
拆分每行
array = line.strip().split(',') #以逗號進行切片,切下來的每個元素儲存在array
字符操作
aa.append() #追加
aa.zfill(num) #字符不足num,在字符開頭充填0
aa.center(num, '+') #字符中心對其,不足num的用+充填
aa.ljust(num, '+') #字符左對齊
aa.rjust(num, '+') #字符右對齊
aa.strip('') #字符開頭和尾部去’'
aa.lstrip('') #字符左邊去‘\’
aa.rstrip('') #字符右邊去‘'
aa.replace('e', 'a') #將字符串中e替換為a
aa.split('e') #通過字符將aa切割為list(其中l(wèi)ist不包括e)
aa.lower() #轉(zhuǎn)換為小寫
aa.upper() #轉(zhuǎn)換為大寫
aa.swapcase() #大小寫互換
aa.capitalize() #首字母大寫