一、文件基本操作
参考资料:[1]python 系统学习笔记(八)---文件操作_ychw365的博客-CSDN博客
(一)代码测试:
import os
print('test1', '\n')
print(os.listdir(os.getcwd()), '\n')
s = 'hello,world\n文本文件读写方法\n文本文件写入方法'
with open('sample.txt', 'w') as fp:
print('# writable()测试文件是否可写:', fp.writable(), '\n')
fp.write(s)
print(os.listdir(os.getcwd()), '\n')
print('test2', '\n')
with open('sample.txt', 'r') as fp:
print('# seekable()是否支持随机访问:', fp.seekable())
print('# readable()当前文件是否可读:', fp.readable(), '\n')
print('# read()读取文件:', '\n', fp.read(), '\n')
print('# seek(offset, [,whence]) 其中whence=0是从文件头,1表示当前位置,2表示文件尾:', fp.seek(3, 0))
print('# tell()返回文件指针当前位置:', fp.tell(), '\n')
print('test1:', '\n')
fp = open('sample.txt', 'r+')
print('# truncate()截取前size个字节:', fp.truncate(5))
print('# read(3)读取前三个字符:', fp.read(3), '\n')
print('当前文件指针位置', fp.tell())
print('read()所读取的内容:', fp.read())
print('seek(0, 0)设置文件指针为文件头:', fp.seek(0, 0))
print('read()读取的内容:', fp.read())
fp.close()
os.remove(os.getcwd() + '\\sample.txt') # 删除sample文件
(二) 测试结果
test1
['.idea', 'filecontent.py']
# writable()测试文件是否可写: True
['.idea', 'filecontent.py', 'sample.txt']
test2
# seekable()是否支持随机访问: True
# readable()当前文件是否可读: True
# read()读取文件:
hello,world
文本文件读写方法
文本文件写入方法
# seek(offset, [,whence]) 其中whence=0是从文件头,1表示当前位置,2表示文件尾: 3
# tell()返回文件指针当前位置: 3
test3:
# truncate()截取前size个字节: 5
# read(3)读取前三个字符: hel
当前文件指针位置 3
read()所读取的内容: lo
seek(0, 0)设置文件指针为文件头: 0
read()读取的内容: hello