6.7读取并输出文本文件
import sys
filename=sys.argv[0]
f=open(filename,'r',encoding='utf8')
line_no=0
while True:
line_no += 1
line=f.readline()
if line:
print(line_no,":",line)
else:
break
f.close
6.8 使用with语句读取并输出文本文件
import sys
filename=sys.argv[0]
line_no=0
with open(filename,'r',encoding='utf8') as f:
for line in f:
line_no+=1
print(line_no,":",line)
f.close()
6.9 文本文件的写入示例
with open("test.txt",'w') as f:
f.write("123\n")
f.writelines(['456\n',"def\n"]) #覆盖之前内容
s=['覆盖之前内容\n',"def\n"]
with open("test.txt",'w') as f:
f.writelines(s)
6.10 文本文件的读取示例
with open('data.txt','r') as f:
for s in f.readlines():
print(s,end='')
6.11 使用reader对象读取csv文件
#6.11
import csv
def readcsv1(csvfilepath):
with open(csvfilepath,newline='') as f:
f_csv =csv.reader(f)
headers=next(f_csv)
print(headers)
for row in f_csv:
print(row)
if __name__=='__main__':
readcsv1(r'scores.csv')
6.12 使用write 对象写入csv文件
import csv
def writecsv1(csvfilepath):
headers = ['学号','姓名','性别','班级','语文','数学','英语']
rows=[('102111','宋颐园','男','一班','72','85','82'),
('102113','王二丫','女','一班','75','82','51')]
with open(csvfilepath,'w',newline='') as f:#打开文件
f_csv=csv.writer(f)
f_csv.writerow(headers)#写入标题
f_csv.writerows(rows)#写入多行数据
if __name__ =='__main__':
writecsv1(r'scores1.csv')
6.13 JSON文件的写入
import json
urls={'baidu':"http://www.baidu.com/",
'sina':'http://www.sina.com.cn/',
'tencent':'http://www.qq.com/',
'taobao':'http://www.taobao.com/'}
with open(r"666.json",'w') as f:
json.dump(urls,f)
6.14 JSON文件的读取
import json
with open(r"666.json",'r') as f:
urls=json.load(f)
print(urls)
6.15随机文件的读写示例
import os
f=open("data.dat",'w+b')
f.seek(0)
f.write(b'hello')
f.write(b'world')
f.seek(-5,os.SEEK_END)
b=f.read(5)
print(b)
6.16文件目录操作示例
import os
#os.mkdir(r"d:\a")#创建目录
#os.makedirs(r"d:\b\c")#创建多级目录
os.getcwd()#显示当前工作目录
os.listdir()#显示目录中的文件/子目录列表
#os.rmdir(r"d:\a")#删除目录
#os.remove(r"d:\b\test.txt")#删除文件
#os.rename(r"d:\b\c",r"d:\b\d")#目录/文件重命名
6.17编写程序(process_txt.py):读取data.txt中的数据,统计分析成绩的个数,最高分,最低分及平均值,并把结果写入result.txt文件中。
scores=[]
txtfilepath='data.txt'
with open(txtfilepath,encoding='utf-8') as f:
for s in f.readlines():
scores.append(int(s))
result_filepath='result.txt'
with open(result_filepath,'w',encoding='utf-8') as f:
f.write("成绩个数:{}\n".format(len(scores)))
f.write("最高分:{}\n".format(max(scores)))
f.write("最低分:{}\n".format(min(scores)))
f.write("平均分:{}\n".format(sum(scores)/len(scores)))
6.18编写程序(read_csv.py):读取data.csv中的数据,统计分析成绩的平均值并打印出结果。
import csv
scores = [] #创建空列表,用于存储从CS
csvfilepath='data.csv'
with open(csvfilepath, newline='') as f:#打开文件
f_csv= csv.reader(f) #创建 csv.reader 对象
headers = next(f_csv) #标题
for row in f_csv: #循环打印各行(列表)
scores.append(row)
print("原始记录:",scores)
scoresData = []
for rec in scores:
scoresData.append(int(rec[2]))
print("成绩列表:",scoresData)
print("平均成绩:",sum(scoresData)/len(scoresData))
6.19基于字典的通讯录
"""简易通讯录程序"""
import os,json
ab = {} #通讯录保存在字典中
#从JSON文件中读取通讯录
if os. path.exists("addressbook.json"):
with open(r'addressbook.json', 'r', encoding = 'utf- 8') as f:
ab = json.load(f)
while True:
print("|---欢迎使用通讯录程序---|")
print("|---1:显示通讯录清单 ---|")
print("|---2:查询联系人资料 ---|")
print("|---3:插人新的联系人 ---|")
print("|---4:删除已有联系人 ---|")
print("|---0:退出 --- -----|")
choice = input('请选择功能菜单(0-4):')
if choice == '1':
if(len(ab) == 0):
print("通讯录为空")
else:
for k, v in ab.items():
print("姓名={},联系电话={}".format(k,v))
elif choice == '2':
name = input("请输人联系人姓名:")
if(name not in ab):
ask = input("联系人不存在,是否增加用户资料(Y/N)")
if ask in ["Y","y"]:
tel = input("请输人用户联系电话:")
ab[name] = tel
else:
print("联系人信息:{}{}".format(name, ab[name]))
elif choice == '3':
name=input("请输人联系人姓名:")
if(name in ab):
print("已存在联系人:{}{}".format(name, ab[name]))
ask=input("是否修改用户资料(Y/)")
if ask in ["Y", "y"]:
tel =input("请输人用户联系电话:")
dict[name] = tel
else:
tel = input("请输入用户联系电话:")
ab[name] = tel
elif choice == '4':
name =input("请输人联系人姓名:")
if(name not in ab):
print("联系人不存在:{}".format(name))
else:
tel = ab.pop(name)
print("删除联系人:{}{}".format(name, tel))
elif choice =='0':#保存到 JSON文件并退出循环
with open(r'addressbook.json', 'w', encoding = 'utf-8') as f:
json.dump(ab,f)
break