2020-12-04
with open("c:/Users/hasee/Desktop/han_demo.txt") as my_file:
contents = my_file.read()
print(contents)
file = open("C:/Users/hasee/Desktop/demo/han_test_demo.txt")
content = file.read()
print(content)
file.close()
上面两种方法都能正确的打开文件并且读取数据,但是在第一种方法中我们可以发现,我们使用了with
关键字。关键字with在不需要访问文件后将其关闭。在这个程序中我们调用了open()
没有调用close()
,我们也可以像第二种那样调用open()和close()来打开和关闭文件,但是这样做时,如果程序存在bug,导致close()语句未执行,文件将不会被关闭,可能会导致文件的数据丢失或者受损。
逐行打印,使用for循环,而不适用read()语句:
file = "C:/Users/hasee/Desktop/demo/han_test_demo.txt"
with open(file) as my_file:
for line in my_file:
print(line.rstrip())
使用with
关键字时,open()返回的文件对象只在with代码块内可用 ,如果要在with代码块外访问文件内容,可以在with代码块内将文件各行存储在一个列表中,并在with代码块外使用该列表。
file = "C:/Users/hasee/Desktop/demo/han_test_demo.txt"
with open(file) as my_file:
lines = my_file.readlines()
for line in lines:
print(line.rstrip())
readlines()
方法从文件中读取每一行,并将其存储在一个列表中,接下来,该列表被存储到变量lines中。
file = "C:/Users/hasee/Desktop/demo/pi_million_digits.txt"
with open(file) as my_file:
lines = my_file.readlines()
pi_string = ""
for line in lines:
pi_string += line
print(pi_string[:20] + "...")
在读取文本时,python将其中的所有文本都解读为字符串,如果要将读取的数字作为数值使用,就必须使用函数int()
将其转换为整数,或者使用float()
转换为浮点数。
file = "C:/Users/hasee/Desktop/demo/pi_million_digits.txt"
with open(file) as my_file:
lines = my_file.readlines()
pi_string = ""
for line in lines:
pi_string += line
birthday = input("你的生日是:")
if birthday in pi_string:
print("你的生日在圆周率里面!")
else:
print("不在。")
2019年3月14日,谷歌宣布称,圆周率现在已经突破3000万亿位,达到了31.4万亿位,这又是一个巨大的突破,但是,依旧没有算尽。
要将文本写入文件,你在调用open()时,需要提供另一个实参。
split()
方法以空格为分隔符,将字符串拆成多个部分,并将这些部分都存储到一个列表中。
通过split()方法可以查询出一个txt文件有多少个单词。
def count_numbers(filename):
try:
with open(filename) as book:
book_contents = book.read()
except:
print("没有" + filename + "这本书")
else:
numbers = book_contents.split()
print(filename + "这本书共有" + str(len(numbers)) + "个单词")
file_name = "C:/Users/hasee/Desktop/demo/han_book.txt"
count_numbers(file_name)
json模块
模块json
能够让你将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
函数json.dump()接收两个实参:要存储的数据以及可用于存储数据的文件对象。
import json
string = [1, 2, 3]
# 指定文件名
louise = "C:/Users/hasee/Desktop/demo/string.json"
with open(louise, "w") as loulou:
json.dump(string, loulou)
我们指定了要将该数字列表存储到其中的文件的名称,通常使用文件扩展名.json
来指出文件存储的数据为JSON格式。
使用json.load()
可以读取数据
import json
file_name = "string.json"
with open(file_name) as loulou:
numbers = json.load(loulou)
print(numbers)
保存和读取用户生成的数据:
import json
# 为文件起名
filename = "username.json"
# 尝试打开文件
try:
with open(filename) as loulou:
username = json.load(loulou)
# 如果之前没有运行过程序会执行
except FileNotFoundError:
username = input("请输入姓名")
with open(filename, "w") as loulou:
json.dump(username, loulou)
print("we will remember you " + username + "!")
# 程序不发生异常会执行的程序
else:
print("welcome back " + username)
我们经常遇到代码能够正常运行,但是需要进一步改进的情况。我们可以将代码划分为完成一系列工作的具体函数,这样的过程被称为重构。