|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
想实现对文件又读又写。。
这里想实现对一个文本,每行的前面加入行号。。
但是使用seek的时候出现问题了。
file_name = 'test.txt'
row_count = 1
file = open(file_name,'r+')
while 1:
text = file.readline().strip()
print(file.tell())
if text:
file.seek(0,1)
file.seek(-len(text),1)
file.write(str(row_count) + ' : '+text + '\n')
row_count += 1
else:
break
file.close()
先读一行后,这个时候的文件指针就知道读一行数据后,然后用seek定位到读这行数据的起始位置,然后再写入一行数据
但是执行后,就报错
Traceback (most recent call last):
File "G:\lujun\daima\python\2\file_test.py", line 12, in <module>
file.seek(-len(text),1)
io.UnsupportedOperation: can't do nonzero cur-relative seeks
但是查手册,
seek(offset, whence=SEEK_SET) Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. Values for whence are:
- SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
- SEEK_CUR or 1 – current stream position; offset may be negative
- SEEK_END or 2 – end of the stream; offset is usually negative
Return the new absolute position.
是可以设置后面那个参数不为0的。
请问各位鱼友,这是什么问题了。
|
|