with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
with open('text_files/filename.txt') as file_object:
file_path = '/home/ehmatthes/other_files/text_files/_filename_.txt'
with open(file_path) as file_object:
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
3.1415926535
8979323846
2643383279
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
pi_string = ''
for line in lines:
pi_string += line.strip() // 删除每行末尾的换行符和原来位于每行左边的空格
print(pi_string)
print(len(pi_string))
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
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")
如果要给文件添加内容,而不是覆盖原有的内容,可以以附加模式打开文件。以附加模式打开文件时,Python不会在返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾。如果指定的文件不存在,Python将为你创建一个空文件。
Python使用称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运行;如果未对异常进行处理,程序将停止并显示traceback,其中包含有关异常的报告。
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
--snip--
while True:
--snip--
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
>>> title = "Alice in Wonderland"
>>> title.split()
['Alice', 'in', 'Wonderland']
12.要让程序静默失败,可像通常那样编写try代码块,但在except代码块中明确地告诉Python什么都不要做。Python有一个pass语句,可用于让Python在代码块中什么都不要做。
def count_words(filename):
"""计算一个文件大致包含多少个单词。"""
try:
--snip--
except FileNotFoundError:
pass
else:
--snip--
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
json.dump(numbers, f) // 写入后,文件内容为:[2, 3, 5, 7, 11, 13]
import json
filename = 'numbers.json'
with open(filename) as f:
numbers = json.load(f)
print(numbers) // [2, 3, 5, 7, 11, 13]
import json
# 如果以前存储了用户名,就加载它。
# 否则,提示用户输入用户名并存储它。
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) # 文件内容为:"xxx"
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {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(f"Welcome back, {username}!")
else:
username = get_new_username()
print(f"We'll remember you when you come back, {username}!")
greet_user()