[英]Is there an easy python approach to fill missing values nth before and nth after
[英]Append to a file after nth byte in python
我需要在第n个字节后附加到文件,而不删除先前的内容。
例如,如果我的文件包含:“ Hello World”
我试图将position(5)写成“ this”,我应该得到
“你好,这个世界”
有什么模式可以打开文件?
目前,我的代码替换了字符
并给“你好这个”
>>> f = open("1.in",'rw+')
>>> f.seek(5)
>>> f.write(' this')
>>> f.close()
有什么建议么?
您无法insert
文件。 通常要做的是:
在python中应该是这样的:
nth_byte = 5
with open('old_file_path', 'r') as old_buffer, open('new_file_path', 'w') as new_buffer:
# copy until nth byte
new_buffer.write(old_buffer.read(nth_byte))
# insert new content
new_buffer.write('this')
# copy the rest of the file
new_buffer.write(old_buffer.read())
现在,您必须在new_buffer
有Hello this world
。 之后,由您决定是用新的还是用新的方法覆盖旧的。
希望这可以帮助!
我认为您想要做的是读取文件,将其分成两个块,然后将其重写。 就像是:
n = 5
new_string = 'some injection'
with open('example.txt','rw+') as f:
content = str(f.readlines()[0])
total_len = len(content)
one = content[:n]
three = content[n+1:total_len]
f.write(one + new_string + three)
您可以使用mmap执行以下操作:
import mmap
with open('hello.txt', 'w') as f:
# create a test file
f.write('Hello World')
with open('hello.txt','r+') as f:
# insert 'this' into that
mm=mmap.mmap(f.fileno(),0)
print mm[:]
idx=mm.find('World')
f.write(mm[0:idx]+'this '+mm[idx:])
with open('hello.txt','r') as f:
# display the test file
print f.read()
# prints 'Hello this World'
mmap
允许您将可变字符串视为一个字符串。 但是它有局限性,例如切片分配必须与长度相同。 您可以在mmap对象上使用正则表达式。
最后,要将字符串插入文件流,需要读取它,然后将字符串插入读取的数据,然后再写回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.