csv, Excel file operations
1. csv file operation
1. Definition
A csv file is called a comma-separated value file: each line of content is separated by a comma between different columns.
The csv file can be opened directly through Excel, and the data can be saved and displayed in the form of rows and columns, but compared with the Excel file, it can only store data, and cannot save formulas and functions.
2.csv file read operation
-
import csv library
import csv
-
open a file
open(csv文件路径, 'r', encoding='utf-8') 可以不用手动关闭文件,文件操作结束就关闭文件。 with open('files/data.csv', 'w', encoding='utf-8', newline='') as f: pass
-
file read operation
1)csv.reader(文件对象): 获取文件内容返回一个迭代器,以列表为单位返回每一行内容。 2)csv.DictReader(文件对象): 获取文件内容返回一个迭代器,以字典为单位返回第二行开始的每一行内容,第一行内容为字典的键,。
-
close file
文件对象.close()
-
Total read operation flow code
import csv # 先导包 # 1)创建打开csv文件 f = open('files/电影.csv', 'r', encoding='utf-8', newline='') # 2)获取文件内容 # (1)csv.reader(文件对象): 获取文件内容返回一个迭代器,以列表为单位返回每一行内容。 # reader1 = csv.reader(f) # print(list(reader1)) # (2)csv.DictReader(文件对象):获取文件内容返回一个迭代器,以字典为单位返回第二行开始的每一行内容,第一行内容为字典的键,。 reader2 = csv.DictReader(f) print(list(reader2)) # 3)关闭文件 f.close()
3. csv file write operation
-
import csv library
-
open a file
open('files/data.csv', 'w', encoding='utf-8', newline='')
-
File write operation: create writer object
1) csv.writer(): Create a writer object, one line corresponds to a list when writing data.
2) csv.DictWriter(): Create a writer object and write data in dictionary units.
-
close file
文件对象.close()
-
total code
with open('files/data.csv', 'w', encoding='utf-8', newline='') as f: # ===========列表写入========== # writer1 = csv.writer(f) # # 一次写入一行 # writer1.writerow(['姓名', '出生日期', '性别', '年龄']) # writer1.writerow(['小明', '19990616', '男', 23]) # # 一次写入多行内容 # writer1.writerows([ # ['小明', '19990616', '男', 23], # ['小花', '19991216', '女', 23] # ]) # ===========字典写入========== writer2 = csv.DictWriter(f, ['姓名', '出生日期', '性别', '年龄']) # 将字典的键写入文件开头 writer2.writeheader() # 一次写入一行内容 writer2.writerow({ '姓名': '小华', '出生日期': '19890101', '性别': '男', '年龄': 33})
2. Virtual environment
1. System environment
安装python就可以为计算机提供一个python的系统环境。
2. Virtual environment
程序员根据自己需要创建的python环境。
能创建虚拟环境的前提:存在系统环境。
3. The role of the environment
1)提供Python解释器
2)提供第三方库
虚拟环境可以让第三方库根据类别或者项目分开管理。
4. Recommendations for using a virtual environment
1)工作时:一个项目一个虚拟环境,且将虚拟环境直接放在项目中。
2)学习时:一类项目一个虚拟环境,不同类别的虚拟环境放在一个地方。
5. Create a virtual environment
-
Create with pycharm (windows)
file -> Settings -> Project -> Python Interpreter
Click the arrow in the red box to drop down, click show all,
and finally click OK to create it. Use this virtual environment to install modules in this environment. -
Create with directive
Three, Excel file operation
1. Know the Excel file
- Workbook: An excel file is a workbook
- Worksheets: There can be multiple worksheets (at least one) in a workbook
- Cell: A cell is the basic unit for saving data in an excel file
- Row and Column Numbers: Determine Cell Positions
2. Excel file read operation
-
import openpyxl library
import openpyxl
-
Open Excel file to create workbook object
openpyxl.open(excel文件路径) openpyxl.load_workbook(文件路径)
-
get worksheet
工作簿对象.active 工作簿对象.['工作表名称']
-
get cell
工作表对象.cell(行号,列号)
-
get cell content
单元格对象.value
-
Get the maximum row number and maximum column number (valid rows and valid columns that hold the data)
工作表对象.max_row 工作表对象.max_column
-
Total Excel file read operation code
import openpyxl # 1)打开excel文件创建工作簿对象 # workbook = openpyxl.open('files/三国人物数据.xlsx') workbook = openpyxl.load_workbook('files/三国人物数据.xlsx') # 获取工作簿中所有的工作表的表名 result = workbook.sheetnames print(result) # ['全部人物数据', '三个国家的武力', '三个国家武将的武力', '三国武将数据', '三国文官数据'] # 2)获取工作表 sheet1 = workbook.active # 获取1 print(sheet1) sheet2 = workbook['三国武将数据'] # 获取2 print(sheet2) # 3)获取单元格 cell1 = sheet2.cell(8, 1) cell2 = sheet2.cell(12, 1) print(cell1, cell2) # 4)获取单元格内容 print(cell1.value) print(cell2.value) # 5)获取最大行号和最大列号(保存了数据的有效行和有效列) # 工作表对象.max_row # 工作表对象.max_column print(sheet2.max_row) print(sheet2.max_column) # 获取表中内容例子 # 获取第一列所有数据 column1 = [] for row in range(1, sheet2.max_row+1): cell = sheet2.cell(row, 1) column1.append(cell.value) print(column1) # 获取第一列到第3列所有的数据 for col in range(1, 4): column = [] for row in range(1, sheet2.max_row+1): cell = sheet2.cell(row, col) column.append(cell.value) print(column)
3. Excel file write operation
-
import openpyxl library
import openpyxl
-
New workbook:
a. Create a new workbook object - Workbook
workbook = openpyxl.Workbook()
Note : Reality in life: To actually create a new workbook, you need to first determine whether the corresponding file of the workbook already exists. If it exists, you do not need to create a new one.
-
Worksheet Operations
a. Create worksheet - create_sheet
工作簿对象.create_sheet(表名)
Note: The actual new table: only create a new table when it is not available, and sometimes open it directly
b. Delete worksheet - remove
工作簿对象.remove(工作表对象) 实际中的删除表:有的时候才删除
-
cell write operation
单元格对象.value = 数据
-
save document
工作簿对象.save(文件路径)
-
The overall process code of excel file writing operation
import openpyxl # 1)新建工作簿 # 方法一:异常捕获 try: workbook = openpyxl.open('files/students.xlsx') except FileNotFoundError: workbook = openpyxl.Workbook() # 2)新建工作表 # a.创建工作表 # 实际中的新建表:没有的时候才新建,有的时候直接打开 if 'Python' in workbook.sheetnames: sheet = workbook['Python'] else: workbook.create_sheet('Python') # b.删除工作表 # 实际中的删除表:有的时候才删除 if 'Sheet1' in workbook.sheetnames: workbook.remove(workbook['Sheet1']) print(workbook.sheetnames) # 3)单元格的写操作 # 单元格对象.value = 数据 java_sheet = workbook['Java'] java_sheet.cell(1,3).value = '电话' # 增加 java_sheet.cell(2,1).value = None # 删除 java_sheet.cell(2,2).value = 'stu003' # 修改 # 4)保存 workbook.save('files/students.xlsx')