with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
两个注意点:
file_object = open('pi_digits.txt')
这种方式则需要手动关闭文件流,手动关闭带来的问题就是假设程序在过程中存在bug,导致close()
语句未执行,文件将不会关闭,就会带来数据丢失或损失的问题,所以这是推荐写法。read()
到达文件末尾时会返回一个空串,显示出来就是空行,想删除该空行,可以使用rstrip()
函数,print(file_object.read().rstrip())
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
print(line.rstrip())
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip)
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string= ''
for line in lines:
pi_stirng += line.strip()
print(pi_string)
print(len(pi_string))
注意点:
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string= ''
for line in lines:
pi_stirng += line.strip()
birthday = input('Enter your birthday, in the form mmddyy:')
if birthday in pi_string:
print('Your birthday appeears in the first million digits of pi!')
else:
print('Your birthday does not appear in the first million digits of pi.')
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
improt json
filename = 'programing.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming")
improt json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
很多初学者都没有在程序中写异常的意识,这会给程序带来很多危险,比如程序突然崩溃,攻击者可能会根据traceback对代码发起攻击,一般在涉及到数据交互,输入输出等地方,都要写异常处理语句。写法如例:
print("Give me two numbers, and I'll devide them.")
print("Enter 'q' to quit.")
while True:
first_number = input(\nFirst number:)
if first_number == 'q':
break
second_number = input(\nSecond number:)
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't dividee by 0!")
else:
pirnt(answer)