文件打开:
contents= file_object.read()
print(contents.rstrip()) //rstrip表示去除content的空格
文件写入
filename='test.txt'
with open(filename,'w') as file_object:// 'w'表示直接覆盖之前的内容 'a'表示的附加到之前的内容
file_object.write('I love programme.\n')
file_object.write('I love creating new game.\n')
异常处理;
try:
print(5/0)
except ZeroDivisionError:
print("you can't devide by zero")
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError://文件类处理异常
msg="Sorry, the file"+filename+"does not exist."
print(msg)
def count_words(filename):
try:
with open(filename) as file_object:
contents=file_object.read()
except FileNotFoundError:
pass //当报错不想有任何提示的时候,就用pass
else:
words=contents.split();
num_words=len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
filenames=['test.txt','guest.txt','guest_book.txt','a.txt']
for file in filenames:
count_words(file)
import json
numbers=[2,3,5,7,9]
filename='numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object)//json.dump表示的是把对象写入到文件中
filename='numbers.json'
with open(filename) as f_obj:
number=json.load(f_obj)//json.load表示的是把文件写入对象
print(number)
测试函数:
import unittest
from pizza import get_formatted_name
def test_first_last_name(self):
formatted_name=get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin')//assertEqual表示的是判断对象和预期的测试结果是否一致
unittest.main()