2017-5-17 文件异常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 文件异常的主要内容,如果未能解决你的问题,请参考以下文章

解决未能加载文件或程序集“Newtonsoft.Json ...."或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)(代码片段

使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段

异常和TCP通讯

2017-5-17 web学习 开发基础

片段中的Android致命异常

mvn命令异常:An error has occurred in Javadoc report generation: Unable to find javadoc command异常已解决(代码片段