#文件路径#相对路径# with open(r'text_files\file_name.txt') as file_object: #此处text_file为正在编写的py文件所在目录的子目录文件夹#绝对路径#with open(r'C:\User\ehamatthes\other_files\text_file\file_name.txt') as object : #此处为计算机内目标文件的完整路径#逐行读取
file_name ='pi_digits.txt'withopen(file_name)as file_object:for line in file_object:print(line.rstrip())#此处方法rstrip()消除每行末尾的换行符#将文件各行存储到列表中withopen(file_name)as file_object:
lines = file_object.readlines()#readlines()方法按行读取文件中每一行,并储存到一个列表中for line in lines:print(line.rstrip())#简单使用文件内容withopen(file_name)as file_object:
lines = file_object.readlines()
pi_string =''for line in lines:
pi_string+= line.strip()print("\n"+pi_string)print(len(pi_string))#读入大型文件内容
file_name ='pi_million_digits.txt'withopen(file_name)as file_object:
lines = file_object.readlines()
pi_string =''for line in lines :
pi_string+= line.strip()print(pi_string[:52]+"...")print(len(pi_string))print(len(pi_string[:52]))
将输出写入到空文件
file_name ="programming.txt"withopen(file_name,"w")as file_object:#open()中第二个实参指定python以何种方式打开文件——'w'-写入模式;'a'-附加模式;'r+'-读取与写入;'r'-读取模式;默认为只读
file_object.write('I love python')
写入多行
withopen(file_name,'w')as file_object:
file_object.write("I love creating new gammes!\n")
file_object.write("I love the world!\n")#write()方法不会在写入的字符后加入换行符
将内容附加到文件末尾
withopen(file_name,"a")as file_object:#'a'-附加模式
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write('I love creating apps that can run in a browser.\n')
异常
#ZeroDivisionError异常——异常为python中一种特殊对象try:#try: 后代码块发生错误则执行except :后代码块print(5/0)except ZeroDivisionError:print("You can't divide by zero!")#使用异常避免崩溃print('Give me two numbers, and I will divide them.')print("Enter 'q' to quit !")whileTrue:
first_num =input("\nFirst number: ")if first_num =="q":break
second_num =input("Second number: ")if second_num =="q":breaktry:
answer =int(first_num)/int(second_num)except ZeroDivisionError:print("You can't divide by 0!")else:print(answer)#else: 块放置try: 块代码成功运行后执行的代码#FileNotFoundError异常
file_name ='alice.txt'#此处alice.txt文件不存在py文件同目录下try:withopen(file_name)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ='Sorry , the file '+file_name+' does not exsit.'print(msg)else:
words = contents.split()#split()方法根据字符串创建列表,默认以空格为分隔符
num_words =len(words)print('The file '+file_name+' has about '+str(num_words)+' words.')#使用多个文件defcount_words(file_name):"""计算一个文件包含多少单词"""try:withopen(file_name)as f_obj:
contents = f_obj.read()except FileNotFoundError:
msg ='Sorry , the file '+file_name+' does not exsit.'print(msg)else:
words = contents.split()
num_words =len(words)print('The file '+file_name+' has about '+str(num_words)+" words")
file_names =['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']for file_name in file_names:
count_words(file_name)#出现异常时一声不吭defcount_words(file_name):"""计算一个文件包含多少单词"""try:withopen(file_name)as f_obj:
contents = f_obj.read()except FileNotFoundError:passelse:
words = contents.split()
num_words =len(words)print('The file '+file_name+' has about '+str(num_words)+" words")
file_names =['alice.txt','siddhartha.txt','moby_dict.txt','little_women.txt']for file_name in file_names:
count_words(file_name)
使用json模块方法存储数据
#写入import json
numbers =list(range(1,10,2))
file_name ='numbers.json'withopen(file_name,'w')as f_obj:
json.dump(numbers,f_obj)#json.dump()函数接受两个实参,一个为存储的数据,一个为存储数据的文件对象实参#读取
file_name ='numbers.json'withopen(file_name)as f_obj:
numbers = json.load(f_obj)#json.load()函数接受文件对象实参print(numbers)#保存与读取用户生成的名字import json
# 如果以前存储了用户名,就加载# 否则,就提示用户输入
file_name ='username.json'try:withopen(file_name)as f_obj:
user_name = json.load(f_obj)except FileNotFoundError:
user_name =input("What is your name? ")withopen(file_name,'w')as f_obj:
json.dump(user_name, f_obj)print('We will remember you when you come back!'+user_name.title()+' !')else:print('Welcome back, '+user_name.title()+" !")#重构——将代码划分为一系列完成具体工作的函数import json
defget_stored_username():"""如果储存了用户名,就返回它,否则返回None"""
file_name ="user_name.json"try:withopen(file_name)as f_obj:
user_name = json.load(f_obj)except FileNotFoundError:returnNoneelse:return user_name
defget_new_username():"""提示用户输入用户名"""
user_name =input("What is your name? ")
file_name ='user_name.json'withopen(file_name,'w')as f_obj:
json.dump(user_name,f_obj)return user_name
defgreet_user():"""问候用户,指出名字"""
user_name = get_stored_username()if user_name:print('Welcome back, '+user_name+' !')else:
user_name = get_new_username()print('We will remember you when you come back! '+user_name+' !')
greet_user()