【Python】讀取各種文檔(txt、csv、excel、pdf)方法


1.讀取txt文件

注意事項:

1..txt文件同下方腳本所在的.py文件需要在同一個文件夾下

1 # coding=utf-8
2 
3 txt讀取
4 with open("1233.txt") as file:
5     for line in file:
6         print(line)

 

2.讀取csv文件

注意事項:

1).csv文件同下方腳本所在的.py文件需要在同一個文件夾下

2).csv文件由來必須是,創建完excel文件后另存為csv文件,如果只是修改后綴名讀取是不能成功讀到csv文件中的內容的。

1 # coding=utf-8
2 import csv
3 
4 csv_file = open('csvfile_input.csv','r')
5 reader=csv.reader(csv_file)
6 for item in reader:
7     print(item)

3)讀取+寫入在一起時候的組合代碼

 1 # 讀取csv文件方式2
 2 csvFile = open("csvfile_input.csv", "r")
 3 reader = csv.reader(csvFile)  # 返回的是迭代類型
 4 data = []
 5 for item in reader:
 6     print(item)
 7     data.append(item)
 8 print(data)
 9 #csvFile.close()
10 
11 # 從列表寫入csv文件
12 csvFile2 = open('csvFile3.csv', 'w', newline='')  # 設置newline,否則兩行之間會空一行
13 writer = csv.writer(csvFile2)
14 m = len(data)
15 for i in range(m):
16     writer.writerow(data[i])
17 csvFile2.close()

 

 

 3.讀取excel文件

文件內容(文件所在位置:E:\script\python-script\TestData.xlsx):

 

 

 1 # -*- coding: utf-8 -*-
 2 
 3 import xlrd
 4 
 5 from datetime import date,datetime
 6 
 7 def read_excel():
 8 
 9     ExcelFile=xlrd.open_workbook(r'E:\script\python-script\TestData.xlsx')
10 
11 #獲取目標EXCEL文件sheet名
12 
13     print(ExcelFile.sheet_names())
14 
15 #------------------------------------
16 
17 #若有多個sheet,則需要指定讀取目標sheet例如讀取sheet2
18 
19 #sheet2_name=ExcelFile.sheet_names()[1]
20 
21 #------------------------------------
22 
23 #獲取sheet內容【1.根據sheet索引2.根據sheet名稱】
24 
25 #sheet=ExcelFile.sheet_by_index(1)
26 
27     sheet=ExcelFile.sheet_by_name('TestCase002')
28 
29 #打印sheet的名稱,行數,列數
30 
31     print(sheet.name,sheet.nrows,sheet.ncols)
32 
33 #獲取整行或者整列的值
34 
35     rows=sheet.row_values(2)#第三行內容
36 
37     cols=sheet.col_values(1)#第二列內容
38 
39     print(cols,rows)
40 
41 #獲取單元格內容
42 
43     print(sheet.cell(1,0).value.encode('utf-8'))
44 
45     print(sheet.cell_value(1,0).encode('utf-8'))
46 
47     print(sheet.row(1)[0].value.encode('utf-8'))
48 
49 #打印單元格內容格式
50 
51     print(sheet.cell(1,0).ctype)
52 
53 if __name__ == '__main__':
54     read_excel()

運行結果:

 

4.讀取pdf文件(暫不研究)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM