1.文件操做
1.1 打開關閉文件
r = open('demo01.txt','r')
r.close()
1.1.1 訪問模式
r : 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。
w : 打開一個文件只用於寫入。若是該文件已存在則將其覆蓋。若是該文件不存在,建立新文件。
a : 打開一個文件用於追加。若是該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容以後。若是該文件不存在,建立新文件進行寫入。
b : 二進制模式,換行符原樣寫入讀出,不轉換
rb : 以二進制格式打開一個文件用於只讀。文件指針將會放在文件的開頭。這是默認模式。
wb : 以二進制格式打開一個文件只用於寫入。若是該文件已存在則將其覆蓋。若是該文件不存在,建立新文件。
ab : 以二進制格式打開一個文件用於追加。若是該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容以後。若是該文件不存在,建立新文件進行寫入。
r+ : 打開一個文件用於讀寫。文件指針將會放在文件的開頭。
w+ : 打開一個文件用於讀寫。若是該文件已存在則將其覆蓋。若是該文件不存在,建立新文件。
a+ : 打開一個文件用於讀寫。若是該文件已存在,文件指針將會放在文件的結尾。文件打開時會是追加模式。若是該文件不存在,建立新文件用於讀寫。
rb+: 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
wb+: 以二進制格式打開一個文件用於讀寫。若是該文件已存在則將其覆蓋。若是該文件不存在,建立新文件。
ab+: 以二進制格式打開一個文件用於追加。若是該文件已存在,文件指針將會放在文件的結尾。若是該文件不存在,建立新文件用於讀寫。
1.2 寫數據 write
w = open('demo01.txt','a+')
w.write("\nhey,i have opened the file")
w.close()
1.3 讀數據 read
read(num) 讀取num個字節的數據,若是沒有
r = open('demo01.txt','r')
content = r.read()
print(content)
r.close()
1.4 讀數據行 readlines
按行將數據一次性讀取,返回一個列表
r = open('demo01.txt','r')
content = r.readlines()
i = 1
for temp in content:
print("%d:%s"%(i,temp))
i += 1
r.close
1.5 讀數據行 readline
讀一行數據
r = open('demo01.txt','r')
i = 1
while True:
#讀一行數據
content = r.readline()
#若是讀到最後一行,就中止
if content is None or content == '':
break;
print("%d:%s"%(i,content))
i+=1
r.close()
1.6 製做文件的備份
import os
from datetime import datetime
# 遍歷打印指定文件夾下全部子文件夾和文件
def eachPath(path,targetPath):
# 獲取指定目錄下的文件夾和文件名字
pathDir = os.listdir(path)
for childDir in pathDir:
# 拼接成完整路徑
child = os.path.join(path,childDir)
targetChild = os.path.join(targetPath,childDir)
print(child)
print(targetChild)
# 若是目標是文件夾,建立文件夾
if os.path.isdir(targetChild):
os.makedirs(targetChild)
# 若是是文件,複製
if os.path.isfile(child):
copyFile(child,targetChild)
# 若是是文件夾,遞歸
else:
eachPath(child,targetChild)
# 給文件加時間戳
def timestampsAdd(fileName):
# 1.提取文件的後綴
fileFlagIndex = fileName.rfind(".")
# 找不到返回-1
if fileFlagIndex < 0:
return;
fileFlag = fileName[fileFlagIndex:]
# 2.獲取原文件名
oldFileName = fileName[:fileFlagIndex]
#構造新文件的名字 原文件名+時間戳+原文件後綴
newFileName = oldFileName+datetime.now().strftime("%Y%m%d")+fileFlag
return newFileName
def copyFile(filePath,targetPath):
# 若是是文件,才複製
if os.path.isfile(filePath):
# 獲取目標文件夾
fileNameIndex = targetPath.rfind("\\")
if fileNameIndex < 0:
return;
targetDir = targetPath[:fileNameIndex+1]
if not os.path.exists(targetDir):
os.makedirs(targetDir)
# 把舊文件中的數據,一行行復制到新文件中
oldFile = open(filePath,'rb')
newFile = open(targetPath,'wb')
for content in oldFile.readlines():
newFile.write(content)
# 關閉文件
oldFile.close()
newFile.close()
path = "E://work//jc//iwms-hn//trunk"
targetPath = 'E://備份//jc//jc'
timeStampsFlag = datetime.now().strftime("%Y%m%d")
targetPath = targetPath+timeStampsFlag
if not os.path.exists(targetPath):
os.makedirs(targetPath)
eachPath(path,targetPath)
1.7 獲取當前讀寫的位置
f = open("E:\\123.txt")
print(f.read(11))
print(f.tell()) #11
f.close()
1.8 定位到某個位置
seek(offset,from)
注:seek只支持二進制文件,因此要用b模式打開
offset:偏移量
from:方向
0 :表示文件開頭
1 :表示當前位置
2 :表示文件末尾
f = open("E:\\123.txt",'rb')
# 從新設置位置:離文件末尾,三字節處
f.seek(-3,2)
print(f.read())
f.close()
1.9 重命名 os.rename(old.new)
默認位置是當前代碼所在的目錄
import os
os.rename("123.txt","abc.txt")
1.10 刪除 os.remove(file)
import os
os.remove("abc.txt")
1.11 建立文件夾 os.mkdir(doc)
注:若是文件夾已經存在,會報錯
import os
createDoc = '123'
if not os.path.exists(createDoc):
os.mkdir(createDoc)
1.12 獲取當前目錄
import os
currentDoc = os.getcwd()
print(currentDoc)
1.13 改變默認目錄
import os
os.chdir("../")
print(os.getcwd())
1.14 獲取目錄列表
返回的是列表
import os
print(os.listdir())
1.15 刪除文件夾
import os
print(os.rmdir('123'))
1.16 批量給文件添加時間戳
"""
批量給文件添加時間戳
"""
import os
from datetime import datetime
'''
flag : 1 添加時間戳; 0 刪除時間戳
'''
def timestampAdd(path,flag):
if os.path.exists(path):
os.chdir(path)
dirlist = os.listdir()
for content in dirlist:
# 若是是文件,進行添加刪除時間戳操做
if os.path.isfile(content):
pointIndex = content.rfind(".")
timeIndex = content.find("_")
# 添加時間戳
if flag == 1:
mark = datetime.now().strftime("_%Y%m%d")
# 文件以前沒有時間戳,插入時間戳
if timeIndex < 0:
newFile = content[:pointIndex] + mark + content[pointIndex:]
# 文件以前有時間戳,更新時間戳
else:
newFile = content[:timeIndex] + mark + content[pointIndex:]
else:
# 文件有時間戳,刪除
if timeIndex >= 0:
newFile = content[:timeIndex] + content[pointIndex:]
# 文件沒有時間戳,不變
else:
newFile = content
# 重命名文件
os.rename(content,newFile)
else:
# 遞歸
timestampAdd(content,flag)
# 遞歸完,將os的當前目錄調回以前的目錄
os.chdir("../")
path = 'C:\\Users\\admin\\Documents\\com\\jc\\idgenerator'
timestampAdd(path,1)