实验七 文件操作基础
- 实验目的
- 掌握文件操作有关函数
- 掌握文件的读写
- 掌握EXCEL,CSV文件操作
- 实验题目
1、假设有一英文文本文件,编写程序读其内容,并将其中的大写字母变为小写字母,小写字母变为大写字母。
f = open(r'd:\1.txt','r')
s = f.readlines()
f.close()
r = [i.swapcase() for i in s]
f = open(r'd:\2.txt','w')
f.writelines(r)
f.close()
2、 编写程序,将包含学生成绩的字典保存为二进制文件,然后再读取内容并显示。
import pickle
d = {' 张三 ':98,'李四 ':90,'王五 ':100}
f = open('score.dat','wb')
pickle.dump(d,f)
f.close
f = open('score.dat','rb')
x = pickle.load(f)
f.close()
print(x)
3、读取一个文件,显示除了以井号(#)开头的行以外的所有行
file = open("D://ceshi.txt",'r')
r = file.readlines()
for i in r:
if i[0] == '#':
continue
else:
print(i)
file.close()
4、读取一个EXCEL文件,并显示文件内容
import sqlite3
cn=sqlite3.connect('plan2.dat')
sql="create table IF NOT EXISTS data(学号 int,姓名 text,年龄 int)"
cn.execute(sql)
import xlrd
ef=xlrd.open_workbook('plan.xls')
sheet=ef.sheets()[0]
rows=sheet.nrows
dl=[]
for i in range(1,rows):
dl.append(tuple(sheet.row_values(i)))
cn.executemany('insert into data values(?,?,?)',dl)
cn.commit()
cur=cn.execute('select * from data')
for x in cur.fetchall():
print(x)
5、读取一个.CSV文件,并显示文件内容,并写回一列均值
import csv
file_path = 'plan.csv'
with open(file_path,'r') as f:
my_reader = csv.DictReader(f)
plan = [plan_item for plan_item in my_reader]
# 提取字典的键
my_key = []
for i in plan[0].keys():
my_key.append(tuple(i)) #针对字典 会返回字典的key组成的tuple
my_keys = my_key[2:3] # 需要求平均的键的集合
for i in my_keys:
temp = [plan_item[i] for plan_item in plan] # 将数据读为列表
myaver = [sum([float(i) for i in temp ])/len(temp)]
myaver.insert(0,"")
myaver.insert(0,"")
# 储存字典
out_path = 'planbak.csv'
with open(out_path, 'w', newline = '') as f:
write_csv = csv.DictWriter(f, my_key)
write_csv.writeheader() # 输入标题
write_csv.writerows(plan) # 输入数据
with open(out_path, 'a', newline = '') as e:
write_csv = csv.writer(e)
write_csv.writerow(myaver)