日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python實(shí)現(xiàn)對(duì)doc,txt,xls文檔的讀寫(xiě)操作_python

作者:心之所向521 ? 更新時(shí)間: 2022-06-04 編程語(yǔ)言

1.python實(shí)現(xiàn)對(duì)doc文檔的讀取

#讀取docx中的文本代碼示例
import docx
#獲取文檔對(duì)象
file=docx.Document("path")
print("段落數(shù):"+str(len(file.paragraphs)))#段落數(shù)為13,每個(gè)回車(chē)隔離一段
?
#輸出每一段的內(nèi)容
for para in file.paragraphs:
? ? print(para.text)
?
#輸出段落編號(hào)及段落內(nèi)容
for i in range(len(file.paragraphs)):
? ? print("第"+str(i)+"段的內(nèi)容是:"+file.paragraphs[i].text)

2.python實(shí)現(xiàn)對(duì)txt文檔的讀取

filename = 'tangqing.txt' # txt文件和當(dāng)前腳本在同一目錄下,所以不用寫(xiě)具體路徑
pos = []
Efield = []
with open(filename, 'r') as file_to_read:
  while True:
    lines = file_to_read.readline() # 整行讀取數(shù)據(jù)
    if not lines:
      break
    p_tmp= [float(i) for i in lines.split()] # 將整行數(shù)據(jù)分割處理,如果分割符是空格,括號(hào)里就不用傳入?yún)?shù),如果是逗號(hào), 則傳入‘,'字符。
    pos = np.array(p_tmp) # 將數(shù)據(jù)從list類(lèi)型轉(zhuǎn)換為array類(lèi)型。
    print(pos)

3.python實(shí)現(xiàn)對(duì)xls表格的讀取

import ?xdrlib ,sys
import xlrd
def open_excel(file= 'path'):
? ? try:
? ? ? ? data = xlrd.open_workbook(file)
? ? ? ? return data
? ? except Exception as e:
? ? ? ? print(str(e))
?
#根據(jù)索引獲取Excel表格中的數(shù)據(jù) ? 參數(shù):file:Excel文件路徑 ? ? colnameindex:表頭列名所在行的索引 ?,by_index:表的索引
def excel_table_byindex(file= 'path/xxx.xls',colnameindex=0,by_index=0):
? ? data = open_excel(file)
? ? table = data.sheets()[by_index]
? ? nrows = table.nrows #行數(shù)
? ? ncols = table.ncols #列數(shù)
? ? colnames = ?table.row_values(colnameindex) #某一行數(shù)據(jù)?
? ? list =[]
? ? for rownum in range(1,nrows):
? ? ? ? ?row = table.row_values(rownum)
? ? ? ? ?if row:
? ? ? ? ? ? ?app = {}
? ? ? ? ? ? ?for i in range(len(colnames)):
? ? ? ? ? ? ? ? app[colnames[i]] = row[i]?
? ? ? ? ? ? ?list.append(app)
? ? return list
?
#根據(jù)名稱(chēng)獲取Excel表格中的數(shù)據(jù) ? 參數(shù):file:Excel文件路徑 ? ? colnameindex:表頭列名所在行的所以 ?,by_name:Sheet1名稱(chēng)
def excel_table_byname(file= 'E:\\個(gè)人文件\\6-desktop\\豐沙點(diǎn)表-配電所.xls',colnameindex=0,by_name=u'電度'):
? ? data = open_excel(file)
? ? table = data.sheet_by_name(by_name)
? ? nrows = table.nrows #行數(shù)?
? ? colnames = ?table.row_values(colnameindex) #某一行數(shù)據(jù)?
? ? list =[]
? ? for rownum in range(1,nrows):
? ? ? ? ?row = table.row_values(rownum)
? ? ? ? ?if row:
? ? ? ? ? ? ?app = {}
? ? ? ? ? ? ?for i in range(len(colnames)):
? ? ? ? ? ? ? ? app[colnames[i]] = row[i]
? ? ? ? ? ? ?list.append(app)
? ? return list
?
def main():
? ?tables = excel_table_byindex()
? ?for row in tables:
? ? ? ?print(row)
? ? ? ? ? ?
?
? ?tables = excel_table_byname()
? ?for row in tables:
? ? ? ?print(row)
? ? ? ? ? ?
?
if __name__=="__main__":
? ? main()

原文鏈接:https://blog.csdn.net/weixin_45564943/article/details/122597099

欄目分類(lèi)
最近更新