@ExcitedSpider
2018-01-30T02:01:05.000000Z
字数 2688
阅读 1222
with open('pai.txt') as file_object:
contents=file_object.read()
print(content.strip())
with open('pai.txt') as file_object:
for line in file_object:
print(line.rstrip())
python read everything in file in string. if there are other data type, use type cast method like int(), float().
Wirte file
with open('pai.txt','w') as file_object:
file_object.writelines("I like pie!")
the second para
='w' writemode
='r' readmode Default Mode
='a' appendmode
='r+' both write and read
only str can be write into file, use str() to cast other data type to str.
first_num=input("First number:")
second_num=input("Second number:")
try:
result=float(first_num)/float(second_num)
except Exception: #ZeroDivisionError
print("you can't divide by zero")
else:
print("Result is "+str(result))
import json
numbers=[2,3,4,5,6,7]
numbers2=[]
filename='numbers.json'
with open(filename,'r+') as json_obj:
json.dump(numbers,json_obj)
with open(filename) as json_obj:
numbers2=json.load(json_obj)
print(numbers2)
#getname.py
def get_formatted_name(first,last):
"""Generate a neatly formatted full name"""
full_name = first+' '+last
return str(full_name).title()
#test.py
import unittest
from getname get_formatted_name
class NameTestCase(unittest.TestCase):
"""测试"""
def test_first_last_name(self):
"""能够正确的处理janis jpplin嘛?"""
formatted_name=get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin')
unittest.main()
method | usage |
---|---|
assertEqual(a,b) | a==b? |
assertNotEqual(a,b) | a!=b? |
assertTrue(x) | x==True? |
assertFalse(x) | x==False? |
assertIn(item,list) | if item in list? |
assertNotIn(item,list) | if item not in list? |
#survey.py
class AnoumousSurvey():
"""匿名问卷调查"""
def __init__(self,question):
self.question=question
self.responses=[]
def show_quesiton(self):
"""show quesiton"""
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)
#test.py
from survey import AnoumousSurvey
import unittest
class TestAS(unittest.TestCase):
"""test for AnoumousSurvey"""
def test_store_single_response(self):
"""测试单个答案是否能被存储"""
question="What language did you like most?"
my_survey=AnoumousSurvey(question)
my_survey.store_response('English')
self.assertIn('English',my_survey.responses)
unittest.main()
def gen_counter(name):
count=[0]
def counter():
count[0] += 1
print('Hello '+name+','+str(count[0])+' access!')
return counter
c=gen_counter('master')
c()
c()
c()
#output:
Hello master,1 access!
Hello master,2 access!
Hello master,3 access!
#variation 'count' will only be access by counter(), so it's very safe