文件操作详解:
文件打开模式:
r:只读模式,不可写,文件指针位于文件开头
w:只写模式,不可读,没有该文件则创建,有则执行truncate后打开
a:追加模式,文件指针放在文件末尾,不可读
r+:读写模式,可读可写,文件指针位于文件开头
w+:写读模式,可读可写,同w模式,没有则创建,有则执行truncate后打开
a+:追加可读模式, 可读可写,文件指针位于文件末尾
b:表示处理二进制文件, 如ab, wb, rb
文件方法:
读写:
read(size=-1):无参数则读取文件的全部内容,结束标志为EOF(特殊情况可能读取不完),参数为读取的字符个数,如果为中文则中文字数,为英文则为字母数,返回读取的内容
readline():读取一行,结束标志为换行符或者EOF,参数同read
readlines():读取全部行,并将每行作为列表中的元素,返回一个列表
write(test):写入文件,返回写入的字符个数,如果文件指针位于文件末尾之外的位置,则会覆盖原文件的内容,但不可在文件中添加内容
writelines():同write,可写入多行
判断:
isatty():如果文件是一个交互终端,则返回True
readable():判断文件是否可读
writable():判断文件是否可写
seekable():判断是否支持随机访问,如果False,则seek(),tell(),truncate()方法会引发错误
其他操作:
close():关闭文件,打开文件后一定要关闭,否则会占用文件句柄
flush():将缓存区的内容直接刷入文件内,而缓存区的取消等待,可以做进度条
seek(cookie, whence=0, /):改变文件指针位置,cookie为位置偏移量,whence为起始位置
>whence == 0:从文件开头
>whence == 1:从当前指针位置
>whence == 2:从文件结尾
tell():返回文件指针的当前位置,不同模式下文件指针同seek
truncate(pos=None):截断文件,默认从开头截断即清空文件,参数表示开始截断的位置,按字节数表示,一个汉字不止一个字节,截断后可能会产生无法解码的错误
fileno():获得文件描述符,是一个数字
detach():将文件对象与文件缓存区剥离,剥离后的文件对象处于无用状态,可作为其他文件的文件对象
文件的其他操作:
文件遍历:
>>> for i in f:
print(i.strip())
直接从开头遍历文件,将文件作为一个迭代器,每行作为迭代对象,进行遍历
需要注意的是,这种遍历实际采用的是next方法,根据定义,next()调用时不能调用tell(),否则会报错:
>>>OSError: telling position disabled by next() call
另外,采用这种方法时,迭代器会对文件进行完整调用,文件指针会自动置于结尾,在遍历过程中对文件进行写或者其他操作时,默认文件指针指向结尾。
with语句:
with open("test.txt", 'r') as f:
a = f.read()
dictionary = eval(a)
——with主要是为了防止程序员调用文件对象时忘记关闭文件而产生的一系列麻烦,
所以在with语句范围内即是对文件的操作,with语句之后就不是该文件的操作,
with会自动关闭文件。
with open('log1') as obj1, open('log2') as obj2:
pass
————多文件的with语句
其他:
如前面所有的知识点可知:
>>>文件操作没有添加功能
>由于文件在内存中是完整储存,且不是列表链表那样可索引以及项目化的,
>所以文件不能直接进行内容的添加
>添加内容的唯一方法只有重新建立一个文件,并在将源文件写入的过程中,将添加的内容写入
>并且将源文件覆盖或者源文件作为上一版本的备份
另外,用文件指针直接修改文件的内容时,要计算好修改的字节数以及所修改的位置,
如汉字与字母所占得字节数不同,如果用一个字母替换一个汉字,则会产生无法解码的错误或者出现乱码
所以,通过文件指针修改文件的方法不推荐,重新创建文件可行性以及安全性更高
文件应用:
with open("test.txt", 'r') as f:
a = f.read()
dictionary = eval(a)
current_layer = dictionary
parent_layer = []
while True:
for i in current_layer:
print(i, end=' ')
if len(current_layer) == 0:
print('Input something to add or back')
else:
print('')
print('Choose the menu ("delete" to delete|"exit" to quit|"edit" to change)')
choice = input('>>>').strip()
if choice in current_layer:
if type(current_layer[choice]) == type(current_layer):
parent_layer.append(current_layer)
current_layer = current_layer[choice]
else:
print(current_layer[choice])
elif choice == 'back':
if parent_layer:
current_layer = parent_layer.pop()
elif choice == 'exit':
break
elif choice == 'delete':
a = input('The item to delete:')
current_layer.pop(a)
elif choice == 'edit':
a = input("Please in put the item you want to change: ")
b = input("Please in put the name of item or value changed: ")
c = input("The type : (item|value) ")
if c == 'item':
current_layer[a].setdefault(b)
current_layer[a][b] = {}
elif c == 'value':
current_layer[a] = b
else:
print('Wrong type')
continue
else:
print('inputting add can add item:')
a = input('>>>').strip()
if a == 'add':
current_layer.setdefault(choice)
current_layer[choice] = {}
else:
continue
a = str(dictionary)
with open("test.txt", 'w') as f:
f.write(a)
实现功能:
1. 多级菜单
2. 文件存储和读取菜单
3. 菜单可人为修改:添加、删除、修改等