'''关键字with在不再需要访问文件时将其关闭'''
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
print("\n")
file_path = '/home/shihao/Desktop/python_work/pi_digits.txt'
with open(file_path) as file_object:
contents = file_object.read()
print(contents.rstrip())
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip())
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
file_name = 'programming.txt'
with open(file_name, 'w') as file_object:
file_object.write("I love proggramming.\n")
file_object.write("I am shihao\n")
file_name = 'programming.txt'
with open(file_name, 'a') as file_object:
file_object.write("I love you!")
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
try:
file_name = 'alice.txt'
with open(file_name) as file_object:
contents = file_object.read()
except FileNotFoundError:
print("The file " + file_name + " not found")
import json
numbers = [2, 3, 5, 7, 11, 13]
file_name = 'numbers.json'
with open(file_name, 'w') as f_obj:
json.dump(numbers, f_obj)
with open(file_name) as f_obj:
numbers = json.load(f_obj)
print(numbers)