python文件操作(一)

一、文件基本操作

参考资料:[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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值