python基础(九)
#文件和异常 ''' 处理文件 错误处理 json,保存用户数据 '''
从文件中读取数据
#读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
''' open接受的参数:要打开文件的名称,在当前所执行的文件所在目录找到指定文件; 函数open()返回一个表示文件的对象,python将这个对象存储在我们将在后面使用的变量中; 使用方法read读取这个文件的全部内容,并将其作为一个长长的字符串存储在变量contents中 ''' with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents.rstrip())
3.1415926535 8979323846 2643383279
#文件路径 with open('text_files/pi_digits.txt') as file_object: contents = file_object.read() print(contents.rstrip())
3.1415926535 8979323846 2643383279
file_path = 'text_files/pi_digits.txt' with open(file_path) as file_object: contents = file_object.read() print(contents.rstrip())
#逐行读取 filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line)
3.1415926535 8979323846 2643383279
filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
3.1415926535 8979323846 2643383279
#创建一个包含文件各行内容的列表 ''' with open()返回的文件对象只在with代码块内可用 要在代码块外访问文件内容,可以将文件的各行存储在一个列表中 '''
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines : print(line.rstrip())
3.1415926535 8979323846 2643383279
#使用文件的内容 filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print(pi_string) print(len(pi_string))
3.1415926535 8979323846 2643383279 36
#删除空格strip filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() print(pi_string) print(len(pi_string))
3.141592653589793238462643383279 32
#包含一百万位的大型文件 filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() print(pi_string[:52] + "...") print(len(pi_string))
3.14159265358979323846264338327950288419716939937510... 1000002
#圆周率中包含你的生日吗 filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.strip() birthday = input("Enter your birthday,in the form mmddyy:") if birthday in pi_string: print("Yes! In!") else: print("Sorry.")
Enter your birthday,in the form mmddyy:0201 Yes! In!
写入文件
保存数据的最简单的方式
将输出写入文件,程序输出终端窗口关闭了,输出也存在
查询,分享,输出处理
#写入空文件 filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.")
'w'以写入模式打开,读取模式'r',附加模式'a',读取和写入文件的模式'r+'
如果你要写入的文件不存在,函数open()将自动创建它,'w'以写入模式,如果文件已经存在,将会被覆盖
#写入多行 filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.") file_object.write("I love creating new games.")
#两行挤在一起 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")
#添加到文件 ''' 给文件添加新的内容,附加模式 ''' filename = 'programming.txt' with open(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n")
异常
异常使用trace-except代码块处理
处理ZoreDivisionError
print(5/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-21-cfd0a335a8dd> in <module>
1 #异常使用trace-except代码块处理
2 #处理ZoreDivisionError
----> 3 print(5/0)
ZeroDivisionError: division by zero
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero.")
You can't divide by zero.
#使用异常避免崩溃 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: ") if second_number == 'q': break answer = int(first_number) / int(second_number) print(answer)
Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 5 Second number: 2 2.5 First number: 5 Second number: 0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-24-c3edc14c8e87> in <module>
10 if second_number == 'q':
11 break
---> 12 answer = int(first_number) / int(second_number)
13 print(answer)
ZeroDivisionError: division by zero
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: print("You can't divide by zero.") else: print(answer)
Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 5 Second number: 0 You can't divide by zero. First number: q
#处理FileNotFoundError异常 filename = 'alice.txt' with open(filename) as f_obj: contents = f_obj.read()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-26-1609d2652e61> in <module>
2 filename = 'alice.txt'
3
----> 4 with open(filename) as f_obj:
5 contents = f_obj.read()
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + "does not exit." print(msg)
Sorry, the file alice.txtdoes not exit.
#分析文本 title = "Alice in WonderIand" print(title.split())
['Alice', 'in', 'WonderIand']
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + "does not exit." print(msg) else: words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")
Sorry, the file alice.txtdoes not exit.
#对变量contents调用方法split(),生成一个列表 #使用多个文件 ''' 多分析几本书,将这个程序的大部分代码转移到一个函数中 ''' def count_words(filename): try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + "does not exit." print(msg) else: words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") filename = 'alice.txt' count_words()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-3efecb085eee> in <module> 16 17 filename = 'alice.txt' ---> 18 count_words() TypeError: count_words() missing 1 required positional argument: 'filename'
def count_words(filename): try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + "does not exit." print(msg) else: words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
#失败时一声不吭, ''' except FileNotFoundError: pass ''' #决定报告那些错误 line.count('X')
6
line = "XXXXXX" line.lower().count('x')
6
存储数据
使用模块json,能够将简单的python数据结构转储到文件中,并在程序再次运行的时候加载该文件中的数据。
还可用于分享
使用json.dump() json.load()
编写一个存储一组数字的简短程序,再编写一个将这些数字读取到内存中的程序。
import json numbers = [2,3,4,7,9] filename = 'numbers.json' with open(filename, 'w') as f: json.dump(numbers, f)
filename = 'numbers.json' with open(filename) as f: numbers = json.load(f) print(numbers)
[2, 3, 4, 7, 9]
#保存和读取用户生成的数据 username = input("What is your name?") filename = 'username.json' with open(filename, 'w') as f: json.dump(username, f) print("hello, " + username + ".")
What is your name?jing hello, jing.
filename = 'username.json' with open(filename) as f: username = json.load(f) print(username)
jing
filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: username = input("What is your name?") with open(filename, 'w') as f: json.dump(username, f) print("hello, " + username + ".") else: print("welcome" + username + ".")
What is your name?jing hello, jing.
#重构 ''' 将代码划分为一系列完成具体工作的函数。 greet_user()所做的不仅仅是问候用户,还在存储了用户名时获取它,而在没有用户名时提示用户输入一个。 ''' import json def greet_user(): filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: username = input("What is your name?") with open(filename, 'w') as f: json.dump(username, f) print("hello, " + username + ".") else: print("welcome" + username + ".") greet_user()
welcomejing.
''' get_stored_username()如果存储了用户名,就返回它,如果没有存储就返回None。 ''' import json def get_stored_username(): filename = 'username.json' try: with open(filename) as f: username = json.load(f) except FileNotFoundError: return None else: return username def greet_user(): username = get_stored_username() if username: print("welcome" + username + ".") else: username = input("What is your name?") with open(filename, 'w') as f: json.dump(username, f) print("hello, " + username + ".") greet_user()
welcomejing.
''' greet_user()欢迎老客户回来,欢迎新客户 get_stored_username()只负责获取存储的用户名 get_new_username()只负责获取并存储新用户名 ''' import json def get_stored_username(): filename = 'username.json' try: with open(filename) as f: username = json.load(f)#获取 except FileNotFoundError: return None else: return username def get_new_username(): username = input("What is your name?") filename = 'username.json' with open(filename, 'w') as f: json.dump(username, f)#存储 return username def greet_user(): username = get_stored_username()#老 if username: print("welcome" + username + ".") else: username = get_new_username()#新 print("hello, " + username + ".") greet_user()
welcomejing.