'''
open('文件名'):在当前执行的文件所在的目录中查找指定文件然后打开
with在不需要访问文件后将其关闭。只管打开文件,在需要的时候使用它并在合适的时候自动关闭。
不建议同时使用open(),close()
read()读取文件的全部内容。read()到达文件末尾时返回一个空字符串。删除空行可以使用.rstrip()方法。
'''
with open('pi_digits') as file_object:
contents = file_object.read()
print(contents)
with open('pi_digits') as file_object:
contents = file_object.read()
print(contents.rstrip())#rstrip()删除字符串末尾的空白#
'''
相对路径:当前运行的程序所在的目录。
with open('text_files\filenema.txt') as file_object:
绝对路径:完整的路径
file_path = 'C:\ehmaththes\other_files\text_files\filename.txt'
with open('file_path') as file_object:
'''
'''
逐行读取:在文件中查找特定信息或者修改本。
'''
file_name = 'pi_digits'
with open(file_name) as file_object:
for line in file_object:
#print(line)#
print(line.rstrip())#删除换行空格#
filename = 'pi_digits'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
'''
使用文件中的内容:删除文件末尾的换行符。
'''
filename = 'pi_digits'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ' '
for line in lines:
pi_string += line.rstrip()#使用文件中的内容:删除文件末尾的换行符。#
print(pi_string)
print(len(pi_string))
'''
删除原来位于每行左边的空格。
'''
filename = 'pi_digits'
with open(filename) as file_object:
lines = file_object.readlines()#将内容存储在列表中#
pi_string = ' '
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
'''
写文件:open(参数1,参数2,。。。)第一个为文件名,第二个为模式:'w'写入模式
'r'读取模式,'a'附加模式,'r+'读取和写入模式。省略模式时,Python将默认为读取模式。
当要写入的文件不存在的时候,将自动创建它。如果模式是'w'打开文件,如果文件已经存在,则原来的文件的内容将会被清除。
'''
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write('I love programming.')
python 只能将字符串写入文本。数字需要加str()转换成字符串#
'''
write()不会在文本末尾添加换行符。
'''
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write('I love programming.')
file_object.write('I love new games.')
让每个字符串单独占一行#
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write('I love programming.\n')
file_object.write('I love new games.\n')
'''
附加到文件:给文件添加内容而不是覆盖原来的文件。如果指定的文件不存在,将自动创建一个空文件。
'''
filename = 'programming.txt'
with open(filename,'a') as file_object:
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')
'''
异常:使用异常避免崩溃。
'''
try:
print(5/0)
except ZeroDivisionError:
print('you cant divide by zero.') ''' print('Give me two number, and I
ll divide them.')
print("Enyer 'q' to quit.")
while True:
first_number = input("\n First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
answer = int(first_number)/int(second_number)
print(answer)
'''
print('Give me two number, and Ill divide them.') print("Enter 'q' to quit.") while True: first_number = input("\n First number: ") if first_number == 'q': break second_number = input("Second number: ") if second_number == 'q': break try: answer = int(first_number) / int(second_number)#可能引发异常的代码# except ZeroDivisionError: print('you can
t divide by zero.')
else:
print(answer)#代码运行成功的才放在else里#
filename = 'alice.txt'
with open(filename) as file_object:
try:
contents = file_object.read()
except FileNotFoundError:
print('you cant find the file.') ''' 分析文本: ''' title = "Alice in Wonderword" title.split()#split()以空格分隔符将字符串拆成多个部分,并将这些字符串存储在列表中。# filename = 'alic.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: print('you can
t find the file.')
else:
#计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print('The file has '+ filename+' has about '+str(num_words)+' words.')
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
print('you can`t find the file.')
else:
words = contents.split()
num_words = len(words)
print('The file has '+ filename+' has about '+str(num_words)+' words.')
filename = 'alic.txt'
count_words(filename)
'''
让程序在异常时一声不吭:用pass语句。
pass语句还充当了占位符,提醒您在程序的某个位置什么也不做,并且以后要在这里做些什么。
'''
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print('The file has '+ filename+' has about '+str(num_words)+' words.')
filenames = ['alic.txt','siddharttha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
'''
存储数据:json让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
使用json在程序之间分享数据。
json.dump()接受两个实参:要存储的数据和可用于存储数据的文件对象。
'''
import json
numbers = [2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
'''
加载存储的信息
'''
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)#json(load()加载文件对象里面的内容并存储到变量numbers里)#
print(numbers)
'''
保存和读取用户生成的数据。
'''
import json
username = input("What is your name: ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print('We`ll remember you when you come back, '+username+'!')
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print('Welcome back, '+username+'!')
'''
如果第一次没有用户名,则会提醒用户输入然后自动创建一个文本保存用户信息
'''
import json
filename = 'username.json'
try:#可能出现错误的情况#
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:#如果出现错误如何操作#
username = input('What is your name?')
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("I will remember you when you come back," + username +'!')
else:#不出现错误如何操作#
print('Welcome back,'+username+'!')
'''
重构:将代码分成一系列完成具体工作的函数
'''
import json
def greet_user():
filename = 'username.json'
try: # 可能出现错误的情况#
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError: # 如果出现错误如何操作#
username = input('What is your name?')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("I will remember you when you come back," + username + '!')
else: # 不出现错误如何操作#
print('Welcome back,' + username + '!')
greet_user()
import json
def ger_stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
username = ger_stored_username()
if username:
print('Welcome back, '+username+'!')
else:
username = input('What is your name? ')
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print('we will remember you when you come back, '+username+'!')
greet_user()
网友评论