1、写入文件
filename = 'program.txt'
with open(filename, 'w') as f_obj: # 以写入模式('w')打开文件,若要写入的文件program.txt不存在,python将自动创建这个文件
f_obj.write("I like the python.\n") # 方法write(),将一行字符串写入到文件中.方法write()不会在写入的文本末尾添加换行符,若你写多行,需要每行都分隔开,需要在写入的字符串后面添加换行符\n
f_obj.write("I will try to learn python everyday.\n")
// 当你运行这个程序时,没有终端输出,但如果打开文件program.txt,将看到如下两行:
I like the python.
I will try to learn python everyday.
2、附加文件
filename = 'program.txt' # 这个文件已存在且包含两行字符串
with open(filename, 'a') as f_obj: # 附加模式'a'将写入的内容附加到文件的末尾,而不是覆盖文件原来文件
f_obj.write("Hopefully someday I could use the python to write some script to work for me.\n")
f_obj.write("To make it come true, I must work harder.\n")
// 输出结果为:
I like the python.
I will try to learn python everyday.
Hopefully someday I could use the python to write some script to work for me.
To make it come true, I must work harder.
3、 异常处理,try-except-else代码块
每当有Python不知所措的错误发生时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继续运行,否则程序遇到异常时就会停止运行。
def count_words(filename):
"""计算一个文件大概包括多少个单词"""
try: # 只有可能发生错误的代码才需要放在try语句中,由于有些文件名有可能不存在或者文件名的输入有误,就有引发错误。因此打开文件的代码块应放在try代码块中
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError: # 若try代码块中的代码运行正常,python将跳过except代码块;若try代码块中的代码导致了错误,python将查找这样的except代码块,并运行其中的代码
print("Sorry, the file " + filename + " does not exist.")
print("Please write the correct file name")
else: # 当try代码块运行成功时,就会运行else中的代码块
words = contents.split() # 方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中。结果是一个包含字符串中所有单词的列表,虽然有些单词可能包括标点
num_words = len(words) # 计算列表长度
print("The file " + filename + " has " + str(num_words) + " words.")
filenames = ['program.txt', 'text.txt', 'reason.txt', 'cat.txt', 'guest.txt'] # 将要分析的文件名存储在一个列表中
for filename in filenames: # 用for循环遍历列表中每个文件名
count_words(filename) # 调用函数
//输出结果为:
The file program.txt has 35 words.
The file text.txt has 3 words.
The file reason.txt has 0 words.
Sorry, the file cat.txt does not exist. # 由于文件cat.txt不存在,因此上面的except代码块中的代码被执行,然后继续运行剩下的程序
Please write the correct file name
The file guest.txt has 2 words.