【发布时间】:2021-12-02 01:49:50
【问题描述】:
我正在尝试将字符串写入和读取到临时文件中,但是当我打印字符串中的每一行时,它每行只输出一个字符(我认为这是因为当我运行for 循环,它将字符串的每一“行”识别为一个单独的字符。
如果我只是执行print(division_text),下面是我的字符串division_text 的sn-p:
Locked VersoToken Tokens- 170,833.00 VSO
LOCKED
Locked 05/02/2021 • Unlocks 10/01/2022
Owner: 0x308D2Ac1Bab7D0211717F969602fBC26D286555A
UNLOCK COUNTDOWN
352D – 9H – 10M – 29S
下面是写入 tmp 文件的内容:
L
o
c
k
e
d
V
e
r
s
o
T
o
k
e
n
.
.
.
我的代码如下:
division_text = 'Locked VersoToken Tokens- 170,833.00 VSO
LOCKED
Locked 05/02/2021 • Unlocks 10/01/2022
Owner: 0x308D2Ac1Bab7D0211717F969602fBC26D286555A
UNLOCK COUNTDOWN
352D – 9H – 10M – 29S
VIEW TX'
with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmp:
print(tmp.name)
tmp.write('{}\n'.format(division_text))
# reopen the file for reading
with open(tmp.name) as tmp:
new_division_text = tmp.read()
for line in new_division_text:
print(line)
os.remove(tmp.name)
print(line) 的输出是我上面写的垂直系列字符。
'{}\n'.format(division_text) 似乎没有任何帮助。
我无法将字符串修改为行列表,因为这样我就无法将列表写入文件,就好像它是我从中读取的 .txt 文件一样。或者我可以吗?
Python/我的电脑怎么知道它是一个文本文件?
【问题讨论】:
标签: python string temporary-files txt