(1)创建txt文档
打开terminal下命令: touch filename.txt
(2)with open(file path) as file_object:
with 表示打开文档之后关闭
open()返回文件对象
(3)read()读取文件
到达文件末尾后会产生空行,可以用rstrip()删除。
(4)readlines()读取每一行,并将其储存在列表中。往往与for循环并行。
file_path=" "
with open(file_path) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
·使用for循环
·函数括号中是(参数),无需定义,它是哑变量-指代输入的参数,不是一个实际存在的变量。
def count_words(filename #参数哑变量无需定义):
"""计算一个文件大致包含多少个单词"""
with open(filename) as f_obj:
contents = f_obj.read()
words = contents.split()
num_words = len(words)
print("The file "+filename+" has about "+str(num_words)+
" words.")
filenames = ['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
split()提取文本
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write("I love python because it can create and modify my programmes.\n")
处理异常的目的是:
(1)不要让复制你代码的人看到你的操作系统的隐私。(2)给用户信息进行提示。
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print(f"You can't divide by zero.")
else:
print(answer)
本章学习了打开文件,读取多个文件,写入文件(写入空文件,附加到文件)以及处理异常(防止隐私泄露,给用户提供信息)。
解决的疑惑是:函数()中的是参数,无需定义。
恭喜你,可以进行小游戏创作了!