首页 > 代码库 > 2017-5-17 文件异常

2017-5-17 文件异常

读取整个文件:

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 文件异常