读取数据
直接读取
#with在不需要访问时自动关闭
#打开项目下的文件,直接读取
#若要读取指定文件,则要输入指定路径:F:\pycharm\project\ReadWrite\pi_digits.txt
with open('pi_digits.txt') as file_object:
contents = file_object.read()
#去空
print(contents.rstrip())
逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
注意事项,创建一个包含文件内容的列表
#因为with返回的对象只能在with下使用,所以我们可以创建一个列表
#将文件内各行的内容储存在列表中,然后使用
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
**#连接成字符串**
pi_string =""
for line in lines:
pi_string += line.strip()
写入文件
#写入文件,内容只能是字符串,数字要str()转
#'w' 每次写入前都会清空文件,再写入姚写入的内容
filename = 'pi_digits.txt'
with open(filename, 'w') as file_object:
file_object.write("python")
#‘a’为附加,写入前不会清空文件,只会在最后附加。
with open(filename, 'a') as file_object:
file_object.write("\npython")
file_object.write("\n附加")
异常简介
#其他程序
try:
可能出错的诱因代码比如 5/0
except ZeroDivisionError:
相当于C#内的message或者catch,提示,或者纠错。
else:
依赖于try内代码必须成功才能执行的代码
#文件读取
try:
except FileNotFoundError:
else: