[TOC]
从文件中读取数据
1.读取整个文件(一个文件夹内)
with open('document.txt') as file_object:
contents = file_object.read()
print(contents)
函数open().要以任何方式使用文件,都得先打开文件,这样才能访问它
函数open()接受一个参数:要打开文件的名称.Python将在当前执行的文件所在的目录里查找指定的文件.
函数open()返回一个表示文件的对象.Python将这个对象储存在我们后面使用的变量中.
关键字with在不需要访问文件后将其关闭.Python---你只管打开文件,并在需要时使用它,Python会在合适的时候自动将其关闭.
相比原始文件,该输出唯一不同地方在于末尾多了一个空行.read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来就是一个空行.
要删除多出来的空行,可在print语句中使用rstrip().
2.文件路径
当你将类似document.txt这样简单文件名传递给函数open()时,Python将在当前执行的文件所在的目录中查找文件.
相对路径:
#Linux和OS X中
with open('text_files/filename.txt') as file_object:
#Windows中
with open('text_files\filename.txt') as file_object:
绝对路径:
#Linux和OS X中
file_path = '/home/kaiser/other_files/filename.txt'
with open(file_path) as file_object:
#Windows中
file_path = '\home\kaiser\other_files\filename.txt'
wiht open(file_path) as file_object:
3.逐行读取
filename = 'filename.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())#rstrip()函数确保没有空行.
4.创建一个包含文件各行内容的列表
filename = 'filename.txt'
with open(filename) as file_object:
lines = file_object.readlines()#方法readlines()从文件中读取每一行,并储存在列表中
for line in lines:
print(line.rstrip())
5.使用文件的内容
filename = 'filename.txt'
with open(filename) as file_object:
lines = file_object.readlines()
line_string = ''
for line in lines:
#在变量line_string储存的字符串中,包含原来位于每行左边的空格,为删除这些空格,可使用strip()而不是rstrip()
line_string += line.strip()
#检查某个字符串是否在line_string中
birthday = input("Enter your birthday,in the orm mmddyy: ")
if birthday in line_string:
print("YES")
else:
print("NO")
print(line_string)
print(line_string[:52]+"...") #文本过长截断字符
print(len(line_string))
6.replace()
message = "I really like dogs."
message.replace('dog','cat')
'I really like cats'
写入文件
1.写入空文件
调用open()时提供了两个实参,第一个实参是打开文件的名称,第二个实参告诉Python以什么模式打开文件
写入模式:'w'.读取模式:'r'.附加模式:'a'.
如果忽略了模式实参,Python默认只读打开文件
写入文件不存在,函数open()将自动创建它.
以写入'w'模式打开文件时,如果指定文件已经存在,Python将在返回文件对象前清空该文件
Python只能将字符串写入文本文件.要将数值数据储存到文本文件中,必须使用str()将其转换为字符串格式.
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
2.写入多行
函数write()不会在你写入的文本末尾添加换行符.
使用\n,空格,制表符和空行来设置这些输出的格式
3.附加到文件
如果你要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件.
附加模式不会在返回文件对象前清空文件,而是添加到行末,如果文件不存在,创建一个空文件.
关于编程的调查
"""询问用户名字,为什么喜欢编程"""
with open("programming.txt",'w') as file_object:
file_object.write("Why you like programming?\n")
isStopping = True
while isStopping:
answerName = input("Who are you? ")
reason = input("Why you like programming? ")
#注意换行
file_object.write(answerName+' say '+reason+"\n")
#结束程序
isAnyone = input("Enter any key to continue or input 'no' to exit: ")
if isAnyone == 'no':
isStopping = False
"""读取文件"""
with open("programming.txt") as file_object:
contents = file_object.read()
print(contents)
异常
Python使用被称为异常的特殊对象来管理程序执行期间发生的错误.每当发生让Python不知所措的错误时,它都会创建一个异常对象.如果你编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告
异常是使用try-except代码块处理的.try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办.
1.处理ZeroDivisionError异常
一种导致Python引发异常的简单错误---一个数字除以0
print(5/0)
#Python无法这样做,因此你将看到一个traceback
Traceback (most recent call lase);
File "division.py",line1,in <module>
print(5/0)
ZeroDivisionError: division by zero
2.使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
如果try代码块中代码运行没问题,Python将跳过except代码块,反之,Python将查找这样的except代码块并运行其中代码
3.使用异常避免崩溃
4.else代码块(try-except-else模式)
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("\nSecond number: ")
if second_number == 'q'
break
#尝试执行
try:
answer = int(first_number) / int(second_number)
#出现异常处理
except ZeroDivisionError:
print("You can't divide by 0!")
#成功执行后
else:
print(answer)
5.处理FileNotFoundError异常
"""读取不存在文件"""
filename = 'alice.txt'
with open(filename) as f_obj:
contents = f_obj.read()
引发异常:
Traceback (most recent call last):
File "alice.py", line 3, in <module>
with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory:'alice.txt'
6.分析文本
方法split(),它根据一个字符串创建一个单词列表.以空格为分隔符将字符串分拆成多个部分,并将这些部分储存到一个列表中.
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)
else:
#计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print("The file "+filename+" has about "+str(num_words)+" words.")
7.使用多个文件
写入函数中:
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file "+filename+" does not exist."
print(msg)
else:
words = contents.spilt()
num_words = len(words)
print("The file "+filename+"has about "+str(num_words)+" words.")
filenames = ['alice.txt','siddhartha.txt','moby_bacek.txt']
for filename in filenames:
count_words(filename)
8.pass
异常时需要什么都不做,可在except中写入pass语句,让Python什么都不做.
网友评论