Python:从入门到实践
文件读取
-
读取全部
with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents)
3.1415926535 8979323846 2643383279 Process finished with exit code 0
-
按行读取
#按行读取 #① filename = 'pi_digits.txt' #② with open(filename) as file_object: #③ for line in file_object: print(line)
3.1415926535 8979323846 2643383279 Process finished with exit code 0
为何会出现这些空白行呢?因为在这个文件中,每行的末尾都有一个看不见的换行符,而print 语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一
个来自print 语句。要消除这些多余的空白行,可在print 语句中使用rstrip() :#按行读取 #① filename = 'pi_digits.txt' #② with open(filename) as file_object: #③ for line in file_object: print(line.rstrip())
3.1415926535 8979323846 2643383279 Process finished with exit code 0
-
创建一个包含文件各行内容的列表
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip())
此时lines为list
3.1415926535 8979323846 2643383279 Process finished with exit code 0
-
使用文件的内容
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 34 Process finished with exit code 0
-
在变量pi_string 存储的字符串中,包含原来位于每行左边的空格,为删除这些空格,可使用strip() 而不是rstrip() :
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 Process finished with exit code 0
-
圆周率值中包含你的生日吗
filename = 'pi_million_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() ❶ birthday = input("Enter your birthday, in the form mmddyy: ") ❷ if birthday in pi_string: print("Your birthday appears in the first million digits of pi!") else: print("Your birthday does not appear in the first million digits of pi.")
Enter your birthdate, in the form mmddyy: 120372 Your birthday appears in the first million digits of pi!
文件写入
-
写入多行(换行符要加)
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")
-
写入但不覆盖(‘a’)
filename = 'programming.txt' with open(filename, 'a') as file_object: file_object.write("I also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.\n")
异常
-
当你认为可能发生了错误时,可编写一个try-except 代码块来处理可能引发的异常。
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
You can't divide by zero! Process finished with exit code 0
如果try 代码块中的代码运行起来没有问题,Python将跳过except 代码块;如果try 代码块中的代码导致了
错误,Python将查找这样的except 代码块,并运行其中的代码,即其中指定的错误与引发的错误相同。 -
else代码块
通过将可能引发错误的代码放在try-except 代码块中,可提高这个程序抵御错误的能力。
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 0!") else: print(answer)
Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 1 Second number: 1 1.0 First number: 1 Second number: 0 You can't divide by 0! First number: q Process finished with exit code 0
我们让Python尝试执行try 代码块中的除法运算,这个代码块只包含可能导致错误的代码。依赖于try 代码块成功执行的代码都放在else 代码块中;在这个示例中,如果除法运算成功,我们就使用else 代码块来打印结果。
except 代码块告诉Python,出现ZeroDivisionError 异常时该怎么办。如果try 代码块因除零错误而失败,我们就打印一条友好的消息,告诉用户如何避免这种错误。 -
完美的使用文件
def count_words(filename): """计算一个文件大致包含多少个单词""" try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." 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)
文件siddhartha.txt不存在,但这丝毫不影响这个程序处理其他文件:
The file alice.txt has about 29461 words. Sorry, the file siddhartha.txt does not exist. The file moby_dick.txt has about 215136 words. The file little_women.txt has about 189079 words.
-
失败时一声不吭
在前一个示例中,我们告诉用户有一个文件找不到。但并非每次捕获到异常时都需要告诉用户,有时候你希望程序在发生异常时一声不吭,就像什么都没有发生一样继续运行。
要让程序在失败时一声不吭,可像通常那样编写try 代码块,但在except 代码块中明确地告诉Python什么都不要做。Python有一个pass 语句,可在代码块中使用它来让Python 什么都不要做:def count_words(filename): """计算一个文件大致包含多少个单词""" try: --snip-- except FileNotFoundError: ❶ pass else: --snip-- filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
The file alice.txt has about 29461 words. The file moby_dick.txt has about 215136 words. The file little_women.txt has about 189079 words
存储数据
-
使用json.dump() 和json.load()
import json numbers = [2, 3, 5, 7, 11, 13] filename = 'numbers.json' with open(filename, 'w') as f_obj: json.dump(numbers, f_obj)
下面再编写一个程序,使用json.load() 将这个列表读取到内存中:
import json filename = 'numbers.json' with open(filename) as f_obj: numbers = json.load(f_obj) print(numbers)
[2, 3, 5, 7, 11, 13] Process finished with exit code 0
目前就先这些吧,还差个游戏项目有空写写咯!