欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實現(xiàn)對doc,txt,xls文檔的讀寫操作

 更新時間:2022年04月01日 16:09:43   作者:心之所向521  
這篇文章主要介紹了python實現(xiàn)對doc,txt,xls文檔的讀寫操作,正如標題所見,文章包括三個部分python實現(xiàn)對doc文檔的讀取、python實現(xiàn)對txt文檔的讀取和python實現(xiàn)對xls表格的讀取,需要的朋友可以參考一下

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

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

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

filename = 'tangqing.txt' # txt文件和當前腳本在同一目錄下,所以不用寫具體路徑
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ù)分割處理,如果分割符是空格,括號里就不用傳入?yún)?shù),如果是逗號, 則傳入‘,'字符。
    pos = np.array(p_tmp) # 將數(shù)據(jù)從list類型轉換為array類型。
    print(pos)

3.python實現(xiàn)對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ù)名稱獲取Excel表格中的數(shù)據(jù) ? 參數(shù):file:Excel文件路徑 ? ? colnameindex:表頭列名所在行的所以 ?,by_name:Sheet1名稱
def excel_table_byname(file= 'E:\\個人文件\\6-desktop\\豐沙點表-配電所.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()

到此這篇關于python實現(xiàn)對doc,txt,xls文檔的讀寫操作的文章就介紹到這了,更多相關python文檔讀寫操作神經(jīng)網(wǎng)絡數(shù)據(jù)準備內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論