1. 程式人生 > >2017-5-17 文件異常

2017-5-17 文件異常

first -1 exception div encoding exceptio pen cond inpu

讀取整個文件:

with open(‘a.txt‘) as file_object:
file_read = file_object.read()
print(file_read)

f = open(‘a.txt‘)
print(f.read())
f.close()

逐行讀取文件:
file_name = (‘a.txt‘)
with open(file_name) as file_object:
for line in file_object:
print(line.rstrip()) rstrip去除尾部空格

file_name = (‘a.txt‘)
with open(file_name) as file_object:
lines = file_object.readlines()

for line in lines:
print(line.rstrip())


file_name = (‘a.txt‘)
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ‘‘
for line in lines:
pi_string += line.rstrip()
print (len(line))
print(pi_string)
print(len(pi_string))


file_name = (‘a.txt‘)
with open(file_name) as file_object:
lines = file_object.readlines()
pi_string = ‘‘
for line in lines:
pi_string += line.strip()

print(pi_string[:100] + ‘...‘)

print(len(pi_string))


如遇到字符集問題:
with open(‘a.txt‘,encoding=‘utf-8‘,errors=‘ignore‘) as f:
file_object = f.readlines()

for line in file_object:
print(line.rstrip())




寫入:
file_name = ‘a.txt‘
with open(file_name,‘w‘,encoding=‘utf-8‘) as f:
f.write(‘i love you‘)
f.write(‘\ni love zhangyiyi‘)

追加到末尾:
file_name = ‘a.txt‘
with open(file_name,‘a‘,encoding=‘utf-8‘) as f:
f.write(‘\ni love you‘)
f.write(‘\ni love zhangyiyi‘)


異常處理:
try:
print(5/0)
except ZeroDivisionError:
print("輸入錯誤")


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 Exception:
print("錯誤")
else:
print(answer)

文件異常:
file_name = ‘c.txt‘
try:
with open(file_name,encoding=‘utf-8‘) as f:
contents = f.read()
except FileNotFoundError:
msg = "文件不存在"
print(msg)







2017-5-17 文件異常