Python的3:惯用的方式来删除文件最后一个字符

问题描述 投票:0回答:1

是否有一个惯用的方式做到这一点?我刚刚升级在Python 2到Python 3,我想我的端口剧本,我得说,我没有什么印象。从我可以告诉,我的代码随便去哪儿

由此

# Not allowed by Python 3 anymore without being in binary mode.
card_names_file.seek(-1, os.SEEK_END)
if card_names_file.read() == ',':
    card_names_file.truncate()

# Go to end of file just to get position index. lawl.
card_names_file.seek(0, os.SEEK_END)
# Create a temporary just to store said index. More lawl.
eof = card_names_file.tell()
# Index one from the back. ugh. w/e, that's fine.
card_names_file.seek(eof - 1, os.SEEK_SET)

# Oh wait, .read() will advance my pointer. Oh hey Python 3 doesn't let me
# use .peek() either. Fantastic. I'll have to read this...
if card_names_file.read() == ',':
    # Then go back to where I was by indexing from front AGAIN
    card_names_file.seek(eof - 1, os.SEEK_SET)
    # Then remove last character.
    card_names_file.truncate()

这是我几乎见过最愚蠢的代码,我已经花了2个半小时,到目前为止试图删除文件背面的性格,这看起来像一个黑客。

另一种选择是,我有一些代码,看起来像这样

# open file
with open(file, a+)
    # do stuff

# open same file
with open(file, w+b)
    # do different stuff

但我实际上并不能得到这工作的。

python python-3.x file readfile truncate
1个回答
2
投票

基础缓冲区确实有你正在寻找一个peek()方法,所以:

f = open('FILE', 'a+')
f.seek(f.seek(0, os.SEEK_END) - 1)
# or with the same effect you can also:
os.lseek(f.fileno(), -1, os.SEEK_END)
# Actually in append mode we could just seek by -1 from where we are
# (cursor at the end after opening)
f.tell()  # just to see...
f.buffer.peek(1)
f.tell()  # ...still where we were

另外,您也可以使用os.pread()。例如:

os.pread(f.fileno(), 1, os.fstat(f.fileno()).st_size - 1)

这并不是因为依托于更高层次的抽象访问文件很地道,但我invoke:“虽然实用性节拍纯洁”

© www.soinside.com 2019 - 2024. All rights reserved.