文件读写
文件:被持久化存储在磁盘上的字符串。
读操作:将文件中的字符串加载进行内存。
写操作:将字符串写入到磁盘中的操作。
open函数:用于写文件。
print(help(open))
参数:
file:文件名
注意路径:绝对路径 相对路径 next\
encoding:指定open函数在读写文件时使用的字符集
windows 默认字符集是 gbk
notepad++ 默认字符集是 utf-8
open函数 在windows上默认为gbk字符集,在Linux上默认是UTF-8
open函数执行后返回一个文件对象
mode:"r"只读模式(默认)
"w"只写模式,文件不存在可以创建文件,文件存在是覆盖文件
"a"追加模式,文件不存在创建文件,文件存在时将内容添加到文件末尾
文件对象 read() 方法默认将文件中所有字符串读取内存,也可根据字符个数读取 read(n) n表示字符个数
文件中的换行也站一个字符。使用"\n"表示。
readline() 按行读取数据
readline()将所有数据按行放到列表中。
f = open(r"路径",mod="r",encoding="utf-8")
foods = f.readlines()
f.close()
print(foods)
foods.insert(1,"物品\n")
writelines(list) 将列表中字符串直接写入到文件
write(string) 将字符串写入到文件
简单电子词典
def load_word(file):
print("开始加载数据...")
f = open(file,encoding="utf-8")
data = f.readlines()
f.close()
print("加载成功!")
return data
def find_word():
data = load_word("word.txt")
while Ture:
w = input("请输入您想要查询的内容,输入Q退出:")
if w =="Q"
break
n = 0
for line in data:
if w in line:
n += 1
print(n,line,end="")
find_word()
input()
加载词库
def load_word(file):
print("正在加载词库...")
f = open(file,encoding="utf-8")
data = f.readlines()
f.close()
print("词库加载成功...")
return data
从词库中查找单词或汉字
def find_word(w,word_list):
count = 0
for line in word_list:
if w in list:
count +=1
print(count,line,end="")
def main():
word_list = load_word("word.txt")
while Ture:
w = input("请输入您要查找的单词或汉字,输入Q退出:")
if w == "Q":
break
find_word(w,word_list)
main()
这篇博客主要介绍了Python中的文件读写操作,包括open函数的使用、读写模式('r'、'w'、'a')、字符集选择以及read、write、readline、writelines等方法的应用。此外,还提到了一个简单的电子词典的实现,用于从词库中查找单词和汉字。

被折叠的 条评论
为什么被折叠?



