https://blog.csdn.net/u011956147/article/details/80369731
創建文件夾:
import os
import shutil
def buildfile(echkeyfile):
if os.path.exists(echkeyfile):
#創建前先判斷是否存在文件夾,if存在則刪除
shutil.rmtree(echkeyfile)
os.makedirs(echkeyfile)
else:
os.makedirs(echkeyfile)#else則創建語句
return echkeyfile#返回創建路徑
#傳入的參數是需要創建文件夾的路徑,比如我想在D盤下創建一個名字為newfile的文件夾,則傳入參數為r’ D:\newfile’。同樣,返回的參數也是r’ D:\newfile’
1
2
3
4
5
6
7
8
9
10
11
12
寫入文本1:
import codecs
def write_txt(txt, path):
f = codecs.open(path, 'a', 'utf8')
f.write(str(txt))
f.close()
# 傳入參數為txt,path;txt為需要寫入的內容,數據類型為字符串,path為寫入的內容,數據類型為字符串。
# 傳入的path需如下定義:path= r’ D:\text.txt’
# f = codecs.open(path, 'a', 'utf8')中,codecs為包,需要用impor引入,’a’表示追加寫入txt,可以換成’w’,表示覆蓋寫入。'utf8'表述寫入的編碼,可以換成'utf16'等。
1
2
3
4
5
6
7
8
寫入文本2(等同於寫入文本1,但是這個比較常用):
import codecs
def writetxt(path, content, code):
with codecs.open(path, 'a', encoding=code)as f:
f.write(content)
return path+' is ok!'
1
2
3
4
5
6
讀取txt:
def read_txt(path):
with open(path, 'r', encoding='utf8') as f:
lines = f.readlines()
return lines
# 表示按行讀取txt文件,utf8表示讀取編碼為utf8的文件,可以根據需求改成utf16,或者GBK等。
# 返回的為數組,每一個數組的元素代表一行,若想返回字符串格式,可以將改寫成return ‘\n’.join(lines)
1
2
3
4
5
6
7
讀取Excel文件:
import xlrd
def read_xls(path):
xl = xlrd.open_workbook(path)
sheet = xl.sheets()[0] # 0表示讀取第一個工作表sheet
data = []
for i in range(0, sheet.ncols): # ncols表示按列讀取
data.append(list(sheet.col_values(i)))
return data
# xlrd為第三方包,可以通過用pip下載,具體操作:打開運行,輸入cmd→在cmd中輸入pip install xlrd,enter →等待安裝完成即可。在后續若存在需要使用的第三方包,都可以通過這種方式下載和安裝。
# 傳入參數為path,path為excel所在路徑。
# 傳入的path需如下定義:path= r’ D:\excel.xlsx’或path= r’ D:\excel.xls’
# col_values(i)表示按照一列中的所有單元格遍歷讀取
# 可以根據需求,把col替換成row,則表示按行讀取
# return data :返回的data是一個二維數組,根據col和row,傳回的數據呈現形式也不同,即row是col的轉置。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
遍歷文件夾:
def file_walker(path):
fileArray = []
for root, dirs, files in os.walk(path):
for fn in files:
eachpath = str(root+'\\'+fn)
fileArray.append(eachpath)
return fileArray
# 傳入參數為path,path為需要遍歷的文件夾路徑。
# return fileArray 返回的是當前文件下所有文件的絕對路徑
---------------------
作者:FelixFuu
來源:CSDN
原文:https://blog.csdn.net/u011956147/article/details/80369731
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!