我正在使用文件数据中的字节数组。我将其打开为'r+b',因此可以更改为二进制文件。
在Python 3.7 docs 中,它解释了 RegExfinditer()可以使用m.start()和m.end()来识别匹配的开始和结束。
在问题Insert bytearray into bytearray Python 中,答案说可以通过使用切片对 bytearray 进行插入。但是当尝试这样做时,会出现以下错误:BufferError: Existing exports of data: object cannot be re-sized.
下面是一个例子:
pat = re.compile(rb'0.?\d* [nN]') # regex, binary "0[.*] n"
with open(file, mode='r+b') as f: # updateable, binary
d = bytearray(f.read()) # read file data as d [as bytes]
it = pat.finditer(d) # find pattern in data as iterable
for match in …Run Code Online (Sandbox Code Playgroud) 我有一个枚举:
pub enum BoxColour {
Red,
Blue,
}
Run Code Online (Sandbox Code Playgroud)
我不仅希望将此值作为 string 获取,而且还希望将该值转换为小写。
这有效:
impl Display for BoxColour {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(match self {
BoxColour::Red => "red",
BoxColour::Blue => "blue",
})?;
Ok(())
}
}
Run Code Online (Sandbox Code Playgroud)
当颜色列表增加时,该列表需要更新。
如果我使用write!宏,似乎不可能操纵结果,因为write!返回一个实例()而不是一个String:
impl Display for BoxColour {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{:?}", self)
}
}
Run Code Online (Sandbox Code Playgroud)
这表明这是通过副作用起作用的,也许我们可以在内存中破解该值的相同位置,但即使这是可能的,也可能不是一个好主意......
我有2个文件:
text.txt
和:
main.py
在main.py,我有以下代码:
for i in range(1,4097):
i = str(i)
file = open("text.txt","w")
file.write(i)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我想从1生成所有号码- 4096,但是当我运行该脚本,它只是写4096在text.txt。
我如何在里面写数字 1 - 4096 text.txt?
(顺便说一句,我做i了一个字符串 ( str()) 因为它有我和错误说 Python 只能写字符串而不是 Intigers:
Traceback (most recent call last):
File "d:\path\app.py", line 14, in <module>
file.write(i)
TypeError: write() argument must be str, not int
Run Code Online (Sandbox Code Playgroud)
)
谢谢
-D一个n我e升