当前位置: 首页 > 后端技术 > Python

Kangrui‘s Python Learning Diary 2020-07-27

时间:2023-03-26 13:52:57 Python

康瑞的Python学习日记2020-07-27学习了文件处理和代码测试后,在“图灵社区”文件处理部分可以免费下载以下文件#建立相对路径的方法如下:#file_path='C:\Users\other_files\text_files\filename.txt'#withopen(file_path)asfile_objectwithopen('text_file\pi_digits.txt')asfile_object:#传递绝对路径contents=file_object.read()print(contents)#后面会有一个空行文本末尾,因为read()到达在文件末尾返回一个空字符串print(contents.rstrip())#逐行读取filename='text_file\pi_digits.txt'withopen(filename)asfile_object:forlineinfile_object:print(line)withopen(filename)asfile_object:lines=file_object.readlines()#读取每一行并将其存储在列表中forlineinlines:print(line.rstrip())pi_string=''forlineinlines:pi_string+=line.rstrip()print(pi_string)#左边还有一个空格print(len(pi_string))pi_string=''forlineinlines:pi_string+=line.strip()print(pi_string)print(len(pi_string))Theoutputresultis:3.1415926535897932384626433832793.1415926535897932384626433832793.1415926535897932384626433832793.1415926535897932384625433832792691.1953238462643383279363.14159265358979323846264338327932检测生日是否在圆周率前百万位。有东西要输入,所以输出filename='text_file\pi_million_digits.txt'withopen(filename)asfile_objectline:lines=readfile_object.每行都存在于列表中pi_string=''forlineinlines:pi_string+=line.strip()print(pi_string[:52]+"...")print(len(pi_string))birthday=input("Enter你的生日,格式为mmddyy:")ifbirthdayinpi_string:print("你的生日出现在圆周率的前百万位!")else:print("失败。")文件写入和读取部分#写回车空filefilename='programming.txt'withopen(filename,'w')asfile_object:#通过写方式打开文件,如果没有文件,则创建一个文件file_object.write("Iloveprogramming.\n")file_object.write("Ilovecreatingnewgames.\n")#每个输入都会覆盖原来的内容#Openwithopen(filename,'a')asfile_object:file_object.write("Ilovefindingmeaninginlargedatabase.\n")file_object.write("Ilovecreatingappsthatruninabrowser.\n")#使用try-except代码块解决异常try:print(5/0)exceptZeroDivisionError:print("Youcan'tdividebyzero!")#不是真正的解决方案,而是继续运行而不报错whileTrue:first_num=input("\nFirstnumber:")iffirst_num=='q':breaksecond_num=input("\nSecondnumber:")try:answer=int(first_num)/int(second_num)exceptZeroDivisionError:print("Youcan'tdividebyzero!")else:print(answer)#失败时,不要说什么:使用pass命令#使用json模块存储数据importjsonnumbers=[2,3,5,7,11,13]filename='number.json'withopen(filename,'w')asf_obj:json.dump(numbers,f_obj)withopen(filename)asf_obj:new_numbers=json.load(f_obj)print(new_numbers)函数测试部分defget_formatted_name(first,last,middle=''):如果中间:full_name=first+''+middle+''+lastelse:full_name=first+''+last('janis','joplin')self.assertEqual(formatted_name,'JanisJoplin')deftest_first_middle_last_name(self):formatted_name=get_formatted_name('janis','joplin','stupid')self.assertEqual(formatted_name,'JanisStupidJoplin')#各种断言方法#assertEqual#assertNotEqual#assertTrue:判断是否为真#assertFalse#assertIn:判断是否在列表中#assertNotIn#方法setup()#用于创建调查对象和答案列表