一般来说,在Python中使用open函数打开文件时,都会在执行文件相同目录下寻找指定文件,如果没有找到指定文件则产生FileNotFoundError。倘若现在我们在该目录新建一个名为file的文件夹,再在该文件夹下储存要打开的文件。此时如果继续使用with open('文件名') as file的方法行不通。此时我们就要用到相对路径。也就是with open('file\要打开的文件名') as file。注意在Linux和OS X中反斜杠要替换为斜杠。
除了使用相对路径让Python去指定位置寻找文件,我们还可以使用绝对位置,也就是这个文件在设备中的具体位置。比如with open('C:\Users\file\要打开的文件名') as file。通常来说绝对路径的长度较长,我们一般把绝对路径赋值给变量后再传递给open函数。
同样的,在绝对路径中,Linux和OS X系统也要使用斜杠而非反斜杠。
逐行读取
有时候我们需要以每次一行的方法输出文件内容。对文件对象使用for循环即可。
filename='pai.txt'
withopen(filename) as file: for line in file: print(line.restrip())
while flag: print('Enter q to quit when type in number') a=input("Please enter the first number:") if a=='q': break b=input('Please enter the second number:') if b=='q': break try: answear=int(a)/int(b) except ZeroDivisionError: print("The second number can't be zero!") else: print(answear)
print("Good Bye!") ''' >>>Enter q to quit when type in number Please enter the first number:5 Please enter the second number:2 2.5 >>>Enter q to quit when type in number Please enter the first number:6 Please enter the second number:0 The second number can't be zero! >>>Enter q to quit when type in number Please enter the first number:q >>>Good Bye! '''
filename='username.json' try: withopen(filename) as file: username=json.load(file) except FileNotFoundError: username=input("What's your name?") withopen(filename,'w') as file: json.dump(username,file) print("We'll remember you when you come back, "+username+" !") else: print("Welcome back, "+username+' !')
defget_stored_username(): filename='username.json' try: withopen(filename) as file: username=json.load(file) except FileNotFoundError: returnNone else: return username defgreet_user(): username=get_stored_username() if username: whileTrue: flag=input("Is your name "+username+' ?(yes or no)') if flag=='yes': print("Welcome back, "+username+" !") break elif flag=='no': get_new_username() break else: print("Please enter only 'yes' or 'no' !") else: username=input("What is your name?") filename='username.json' withopen(filename,'w') as file: json.dump(username,file) print("We'll remember you when you come back, "+ username+" !")
defget_new_username(): username=input("What is your name?") filename='username.json' withopen(filename,'w') as file: json.dump(username,file) print("We'll remember you when you come back, "+ username+" !")
greet_user() ''' >>>Is your name Adam Ben ?(yes or no) 666 >>>Please enter only 'yes' or 'no' ! Is your name Adam Ben ?(yes or no) no >>>What is your name? JJG >>We'll remember you when you come back, JJG ! ''' ''' >>>Is your name JJG ?(yes or no) yes >>>Welcome back, JJG ! '''
defshow_results(self): '''输出回答''' print("survey results:") for response inself.responses: print('- '+response)
现在我们编写一个程序来使用这个类。
from survey import AnonymousSurvey
question="What language did you first learn to speak?" my_survey=AnonymousSurvey(question)
my_survey.show_question() print("Enter 'q' to quit at any time.\n") whileTrue: response=input("Language: ") if response=='q': break my_survey.store_response(response)
print("\nThank you to everyone who participate in our survey!") my_survey.show_results() ''' >>>What language did you first learn to speak? Enter 'q' to quit at any time. Language: Chinese Language: English Language: Japanese Language: q Thank you to everyone who participate in our survey! survey results: - Chinese - English - Japanese '''
import unittest from survey import AnonymousSurvey
classTestAnonymouseSurvey(unittest.TestCase):
deftest_store_single_response(self): question="What language did you first speak?" my_survey=AnonymousSurvey(question)#实例化my_survey my_survey.store_response("Chinese")#传入实参"Chinese"给方法
import unittest from survey import AnonymousSurvey
classTestAnonymouseSurvey(unittest.TestCase):
deftest_store_single_response(self): question="What language did you first speak?" my_survey=AnonymousSurvey(question) my_survey.store_response("Chinese")
self.assertIn("Chinese",my_survey.responses)
deftest_store_three_response(self): question="What language did you first speak?" my_survey=AnonymousSurvey(question) responses=['English','Spanish','Mandarin'] for response in responses: my_survey.store_response(response)
for response in responses: self.assertIn(response,my_survey.responses)
unittest.main() ''' >>>.. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK '''
deftest_store_three_response(self): for response inself.responses: self.my_survey.store_response(response) for response inself.responses: self.assertIn(response,self.my_survey.responses)
unittest.main() ''' >>>.. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OK '''