- 實驗目的
- 掌握文件操作有關函數
- 掌握文件的讀寫
- 掌握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)