11. 文件读写
#例1
with open('pi_digits.txt') as file_object: #open()将返回一个表示文件pi_digits.txt的对象
contents = file_object.read() #用read()读取文件的全部内容,且解读为字符串
print(contents)
#相对路径
with open('text_files\pi_digits.txt') as file_object: #假设文件在text_files文件夹中
for line in file_object: #逐行读取
print(line.rstrip()) #删除右端空格
#绝对路径
file_path = r'C:\Users\Xlh\Desktop\Python学习\text_files\pi_digits.txt'
#其中r是为了避免反斜杠被视为转义符
with open(file_path) as file_object:
lines = file_object.readlines() #lines是个列表
pi_string = ''
for line in lines:
pi_string += line.strip() #删除两端空格
print(pi_string)
#例2
filename = "programming.txt"
with open(filename,'w') as file_object: #以写入模式打开文件,默认的只读模式
file_object.write("I love programming.\n") #只能将字符串写入文本文件
file_object.write("I love creating new games.\n")
#例3
filename = "programming.txt"
with open(filename,'a') as file_object: #以附加模式打开文件,即向文件中追加文本
file_object.write("I also love finding meaning in large datasets.\n")
file_object.close()
12. 文件路径相关操作
import os.path
os.path.join("C:\\user","Desktop") #组合路径
parent_path,name = os.path.split("C:\\user\\Desktop") #分解路径
print(parent_path)
print(name)
os.path.splittext("image.jpg") #分解出拓展名
os.listdir("C:\\Users\\xlh") #获得目录下的所有条目
os.path.isfile("image.jpg") #如果文件存在则返回True
os.path.isdir("Desktop") #如果目录存在则返回True
os.remove("junk.dat") #删除文件
#改变文件的权限可用os.chmod函数
os.mkdir("C:\\Users\\xlh") #创建空目录,前提是父目录必须存在
os.makedirs("C:\\Users\\xlh") #若父目录不存在则重新创建
os.rmdir("C:\\Users\\xlh") #删除目录(仅对空目录有效)
#重命名、移动、复制和删除文件
import shutil
shutil.move("sever.log","server.log.backup") #重命名文件
shutil.move("mail.txt","C:\\DATA\\") #移动文件到另一目录下
shutil.copy("important.dat","C:\\backups") #将文件复制到新目录下
shutil.rmtree("C:\\Users\\xlh") #删除目录(谨慎使用,因为即使目录有文件也一并删除)
#例4
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number:")
if first_number == 'q':
break
second_number = input("Second number:")
try:
answer = int(first_number)/int(second_number)
except ZeroDivisionError: #出现ZeroDivisionError异常时该怎么办,且程序继续运行
pass #pass表示什么都不做
#print("You can't divide by zero!")
else:
print(answer)
#例5
title = "Alice in Wonderland"
title.split() #以空格为分隔符将字符串拆分成多个部分
#例6
import json
numbers = [2,3,5,7,11,3]
filname = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj) #将数据存储在文件对象中
with open(filename) as f_obj:
numbers = json.load(f_obj) #读取到内存中
print(numbers)
#2.测试代码
#例1
import unittest
def get_formatted_name(first_name,last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
class NamesTestCase(unittest.TestCase): #继承unittest.TestCase类
"""测试get_formatted_name函数"""
def test_first_last_name(self): #以test_打头的方法将自动运行
"""能够正确处理姓名吗?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin') #若相等返回OK,表示测试通过
unittest.main()
#例2
class AnonymousSurvey():
"""手机匿名调查问卷的答案"""
def __init__(self,question):
"""存储一个问题,并为存储答案做准备"""
self.question = question
self.response = []
def show_question(self):
"""显示调查问卷"""
print(self.question)
def store_response(self,new_response):
"""存储单份调查答案"""
self.responses.append(new_response)
def show_results(self):
"""显示所有收集到的答案"""
print("Survey results:")
for response in self.responses:
print('- ' + response)
#将该类保存为surve.py
from survey import AnonymousSurvey
class TestAnonymousSurvey:
question = "What language did you first learn to speak?"
my_survey = AnonymousSurvey(question)
my_survey.show_question()
pritn("Enter 'q' at any time to quit.\n")
while True:
response = input("Language:")
if response == 'q':
break
my_survey.store_response(response)
print("\nThank you to everyone who participated in the survey!")
my_survey.show_results()
#例3
class TestAnonymousSurvey:
def setUp(self):
question = "What language did you first learn to speak?"
self.my_survey = AnonymousSurvey(question)
self.responses = ['English','Spanish','Mandarin']
def test_store_single_response(self):
"""测试单个答案会被妥善的存储"""
self.my_survey.store_response(self.responses[0])
self.assertIn(self.responses[0],self.my_survey.responses)
def test_store_three_response(self):
"""测试三个答案会被妥善的存储"""
for response in self.responses:
self.my_survey.store_response(response)
for response in self.responses:
self.assertIn(response,self.my_survey.responses)
unittest.main()