标签: write

Python 3.73 插入到 bytearray ="对象不能重新调整大小"

我正在使用文件数据中的字节数组。我将其打开'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)

regex arrays file python-3.x write

5
推荐指数
1
解决办法
249
查看次数

如何以小写形式显示枚举?

我有一个枚举:

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)

这表明这是通过副作用起作用的,也许我们可以在内存中破解该值的相同位置,但即使这是可能的,也可能不是一个好主意......

enums lowercase rust display write

1
推荐指数
2
解决办法
81
查看次数

Python只在txt文件中写入For语句的最后一位数字

我有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,但是当我运行该脚本,它只是写4096text.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一个ne

python string integer for-loop write

0
推荐指数
1
解决办法
49
查看次数

标签 统计

write ×3

arrays ×1

display ×1

enums ×1

file ×1

for-loop ×1

integer ×1

lowercase ×1

python ×1

python-3.x ×1

regex ×1

rust ×1

string ×1