习题7.1-7.5.md

#读取文本文件
print("Opening and closing the file.")
text_file = open("read_it.txt","r")
text_file.close()

print("\nReading characters from the file.")
text_file = open("read_it.txt","r")
print(text_file.read(1))
print(text_file.read(5))
text_file.close()

print("\nReading the entire file at once.")
text_file = open("read_it.txt","r")
whole_thing = text_file.read()
print(whole_thing)
text_file.close()

print("\nReading characters from a line.")
text_file = open("read_it.txt","r")
print(text_file.readline(1))
text_file.close()

print("\nReading one line at a time.")
text_file = open("read_it.txt","r")
print(text_file.readline())
print(text_file.readline())
text_file.close()

print("\nReading the entire file into a list.")
text_file = open("read_it.txt","r")
lines = text_file.readlines()
print(lines)
print(len(lines))
for line in lines:
    print(line)
text_file.close()

print("\nLooping through the file,line by line.")
text_file = open("read_it.txt","r")
for line in text_file:
    print(line)
text_file.close()

Opening and closing the file.

Reading characters from the file.
l
ine1


Reading the entire file at once.
line1
This is line2
That makes this lin3

Reading characters from a line.
l

Reading one line at a time.
line1

This is line2


Reading the entire file into a list.
['line1\n', 'This is line2\n', 'That makes this lin3']
3
line1

This is line2

That makes this lin3

Looping through the file,line by line.
line1

This is line2

That makes this lin3
#写入文件
print("Creating a text file with the write() method.")
text_file = open("write_it.txt","w")

text_file.write("Line1\n")
text_file.write("This is line2\n")
text_file.write("That makes this line3\n")
text_file.close()

print("\nReading the newly created file.")
text_file = open("write_it.txt","r")
print(text_file.read())
text_file.close()

print("\nCreating a text file with the writelines() method")
text_file = open("write_it.txt","w")

lines = ["Line1\n",
       "This is line2\n",
       "That makes this line3\n"]
text_file.writelines(lines)
text_file.close()

print("\nReading the newly created file.")
text_file = open("write_it.txt","r")
print(text_file.read())
text_file.close()
Creating a text file with the write() method.

Reading the newly created file.
Line1
This is line2
That makes this line3


Creating a text file with the writelines() method

Reading the newly created file.
Line1
This is line2
That makes this line3

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#数据序列化处理
import pickle,shelve
#pickle和shelve模块对复杂数据进行序列化处理并保存到文件
print("Picking lists.")
variety = ["sweet","hot","dill"]
shape = ["whole","spear","chip"]
brand = ["Claussen","Heinz","Vlassic"]

f = open("picklesl.dat","wb")
pickle.dump(variety,f)
pickle.dump(shape,f)
pickle.dump(brand,f)
f.close()

print("\nUnpickling lists.")
f = open("picklesl.dat","rb")
variety = pickle.load(f)
shape = pickle.load(f)
brand = pickle.load(f)
print(variety)
print(shape)
print(brand)
f.close()

print("\nShelving lists.")
s = shelve.open("pickles2.dat")
s["variety"] = ["sweet","hot","dill"]
s["shape"] = ["whole","spear","chip"]
s["brand"] = ["Claussen","Heinz","Vlassic"]
s.sync()#确保数据写入

print("\nRetrieving lists from a shelved file:")
print("brand -",s["brand"])
print("shape -",s["shape"])
print("variety -",s["variety"])
s.close()
Picking lists.

Unpickling lists.
['sweet', 'hot', 'dill']
['whole', 'spear', 'chip']
['Claussen', 'Heinz', 'Vlassic']

Shelving lists.

Retrieving lists from a shelved file:
brand - ['Claussen', 'Heinz', 'Vlassic']
shape - ['whole', 'spear', 'chip']
variety - ['sweet', 'hot', 'dill']

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#异常处理 try/except
try:
    num = float(input("Enter a number:"))
except:
    print("Something went wrong!")
Enter a number:hi
Something went wrong!

在这里插入图片描述

#为异常命名
try:
    num = float(input("Enter a number:"))
except ValueError:
    print("That was not a number!")
Enter a number:w
That was not a number!
# 处理多种异常
for value in (None,"Hi"):
    try:
        print("Attempting to convert",value,"--->",end=" ")
        print(float(value))
    except(TypeError,ValueError):
        print("Something went wrong!")
Attempting to convert None ---> Something went wrong!
Attempting to convert Hi ---> Something went wrong!
#获取异常的参数
try:
    num = float(input("Enter a number:"))
except ValueError as e:
    print("That was not a number!Or as Python would say...")
    print(e)
    
Enter a number:e
That was not a number!Or as Python would say...
could not convert string to float: 'e'
#添加else语句,当try块id代码没有任何异常时执行
try:
    num = float(input("Enter a number:"))
except ValueError:
    print("That was not a number!")
else:
    print("You entered the number:",num)
Enter a number:2
You entered the number: 2.0

猜你喜欢

转载自blog.csdn.net/DMU_lzq1996/article/details/82984675
7.1
7.5