文件和异常
读取文件内容:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
无需关闭,python会帮你做这个事
python读取末尾时,会返回一个空字符串,表现为多一个空行,去除空行:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Linux读取某路径下文件:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
with open(file_path) as file_object:
window读取某路径下文件:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
逐行读取文件内容:
with open('w.py') as file_test:
for line in file_test:
print(line)
逐行读取文件内容(去除空行):
with open('w.py') as file_test:
for line in file_test:
print(line.rstrip())
with读取的文件对象只在with代码块发生作用,外部使用时需要保存到列表中
filename = 'w.py'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
写入文件:
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, '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:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
try-else逻辑(else是try成功时执行):
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)