读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())
发现结果有空行出现
windows系统使用的是反斜杠,linux系统使用的是斜杠
print("absolute path to find files")
file_path = 'D:\Icode\forPython\1.txt'
with open(file_path) as file_object:
contents = file_object.read()
#print(contents)
print(contents.rstrip())
每一行进行输出文件内容
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
for line in file_object:
print(line)
在代码外面使用每一行
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
lines = file_object.readline()
for line in lines:
print(line.rstrip())
使用文件的内容,并判断
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
lines = file_object.readline()
pi_string = ''
for line in lines:
pi_string +=line.rstrip()
birth = input("please input your birthda:")
if birth in pi_string:
print("yes")
else:
print("no")
print(pi_string)
print(len(pi_string))
写入新的文件
Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数
str()将其转换为字符串格式。
第二个实参(‘w’)告诉Python,我们要以写入模式打开这个文件。打开文件时,可指定读取模
式(‘r’)、写入模式(‘w’)、附加模式(‘a’)或让你能够读取和写入文件的模式(‘r+’)。如果
你省略了模式实参,Python将以默认的只读模式打开文件。
file_name = 'programmingData.txt'
with open(file_name,'r+') as file_object:
file_object.write(" I love wpfei!")
file_name = 'programmingData.txt'
with open(file_name,'r+') as file_object:
file_object.write(" I love wpfei!\n")
file_object.write(" I love hhhh!")
附加到的文件后面
只需要很简单的操作,将控制的参数改为‘a’即可
异常
Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知
所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运行;
如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
print(2/0)
Traceback (most recent call last):
File "d:\Icode\forPython\02file_open.py", line 1, in <module>
print(2/0)
ZeroDivisionError: division by zero
try:
print(2/0)
except ZeroDivisionError:
print("you can not division by zero!!!")
[Running] python -u "d:\Icode\forPython\02file_open.py"
you can not division by zero!!!
[Done] exited with code=0 in 0.154 seconds
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
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)
可以写出十分健壮的程序
文件查找不到的异常
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)