文件读写主要模式:
tell() 函数用于判断文件指针当前所处的位置,而 seek() 函数用于移动文件指针到文件的指定位置。
文件对象属性函数:
读操作:
fp = open('temp.txt', 'r')
print(fp.read()) #读取所有内容
fp.close()
print('-----')
fp = open('temp.txt', 'r')
print(fp.read(5)) #读取指定bytes 包括\n
fp.close()
print('-----')
fp = open('temp.txt', 'r')
print(fp.readline()) #读取一行 包括\n
fp.close()
print('-----')
fp = open('temp.txt', 'r')
print(fp.readlines()) #读取所有行,注意:最后一行只有\n不用读
fp.close()
输出:
nizhenhao
hao
ma
-----
nizhe
-----
nizhenhao
-----
['nizhenhao\n', 'hao\n', 'ma\n']
写操作:
fp = open('temp.txt', 'w+')
fp.write('hello')
fp.seek(0)
print(fp.read())
fp.close()
print('-----')
fp = open('temp.txt', 'w+')
fp.writelines(['hello\n','world\n'])
fp.seek(0) #定位文件指针位置
print(fp.read())
fp.close()
print('-----')
输出:
hello
-----
hello
world
-----