python基础(5)-文件操作

时间:2021-11-19 16:43:27

文件(file)操作

创建文件

python基础(5)-文件操作

verse.txt:

床前明月光
疑是地上霜

open(path(文件路径),mode(模式:r/r+[读],w/w+[写],a/a+[追加])):返回文件句柄(对象)

verse_file = open('verse.txt','r',encoding="utf-8")

r/r+[读],w/w+[写],a/a+[追加]的区别

mode 可做操作 若文件不存在 是否覆盖
r 只读 报错 -
r+ 读写 报错
w 只写 创建
w+ 读写 创建
a 只写 创建 追加
a+ 读写 创建 追加

readlines():获取所有行,返回list

 verse_file = open('verse.txt','r',encoding="utf-8")
 print(verse_file.readlines())
 verse_file.close()
 #result:
     #['床前明月光\n', '疑是地上霜']

read():读取所有字符,返回string

 verse_file = open('verse.txt','r',encoding="utf-8")
 print(verse_file.read())
 verse_file.close()
 #result:
     # 床前明月光
     # 疑是地上霜

遍历文件最优法(懒加载)

verse_file = open('verse.txt','r',encoding="utf-8")
for row in verse_file:
    print(row.strip())
#result:
    # 床前明月光
    # 疑是地上霜

write():写入.当mode为'w'[写]时,会清空之前的内容再写入;当mode为'a'[追加]时,会在原来基础上继续追加写入

 verse_file = open('verse.txt','w',encoding="utf-8")
 input_str = '举头望明月\n低头思故乡'
 verse_file.write(input_str)
 verse_file.close()
 """
 verse.txt:
     举头望明月
     低头思故乡
 """
 verse_file = open('verse.txt','a',encoding="utf-8")
 input_str = '举头望明月\n低头思故乡'
 verse_file.write(input_str)
 verse_file.close()
 """
 verse.txt:
     床前明月光
     疑是地上霜举头望明月
     低头思故乡
 """

seek(position):定位光标位置

verse_file = open('verse.txt','r',encoding="utf-8")
verse_file.seek(6)#utf-8中一个中文字符占3个字节
print(verse_file.read())
verse_file.close()
"""
 verse.txt:
    明月光
    疑是地上霜
"""

tell():获取光标位置

 verse_file = open('verse.txt','r',encoding="utf-8")
 verse_file.seek(6)
 print(verse_file.tell());#result:6

练习

多级目录文件持久化增删改查

python基础(5)-文件操作

address.dic:

{}

file.py:

 file = open('address.dic', 'r', encoding='utf8')
 history_list = []
 address_dic = eval(file.read())
 while True:
     print('---当前地址---')
     for current in address_dic:
         print(current)
     choose = input('请选择---0:返回上一层,1:新增,2:删除,3:修改,4:查询,5:保存退出:')
     ':
         if history_list:
             address_dic = history_list.pop();
     ':
         insert_name = input('请输入新增项名称:')
         if insert_name in address_dic:
             print('新增失败!该名称项已存在!')
             continue;
         else:
             address_dic[insert_name] = {}
     ':
         delete_name = input('请输入删除项名称:')
         if delete_name not in address_dic:
             print('删除失败!该名称项不存在!')
             continue;
         else:
             del address_dic[delete_name];
     ':
         modify_name = input('请输入修改项名称:')
         if modify_name not in address_dic:
             print('修改失败!该名称项不存在!')
             continue;
         else:
             modify_to_name = input('请输入修改后的名称:')
             modify_value = address_dic[modify_name];
             address_dic[modify_to_name] = modify_value
             del address_dic[modify_name]
     ':
         select_name = input("请输入查询项名称:")
         if select_name not in address_dic:
             print('查询失败!该名称项不存在!')
             continue;
         else:
             history_list.append(address_dic)
             address_dic = address_dic[select_name]
             if not address_dic:
                 print('当前无地址')
     ':
         file = open('address.dic', 'w+', encoding='utf8')
         if history_list:
             file.write(str(history_list[0]))
         else:
             file.write(str(address_dic))
         file.close();
         break;
     else:
         print("输入错误")

运行结果:

python基础(5)-文件操作

address.dic:

 {'湖北': {'武汉': {}}, '广东': {'深圳': {}}}

扩展

eval(str):可将对应格式字符串转成相应类型对象.例:

 dic_str = "{'1':'a','2':'b'}"
 list_str = "['1','2','3']"
 dic = eval(dic_str)
 list = eval(list_str)
 print(dic,type(dic))
 print(list,type(list))
 #result:
     # {'1': 'a', '2': 'b'} <class 'dict'>
     # ['1', '2', '3'] <class 'list'>

with:类似C#中Using块,当前块执行完释放对象.下面两块代码等价.

 with open("test",'r') as file:
     file.read();
 file = open("test",'r')
 file.read()
 file.close()

编码与解码

推荐博客:https://www.cnblogs.com/OldJack/p/6658779.html