【问题标题】:Python writing one character per line instead of entire string on temporary filePython在临时文件上每行写入一个字符而不是整个字符串
【发布时间】: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


    【解决方案1】:

    read() 将文件的全部内容读取到单个数组中,这就是为什么当您遍历它时,它会将每个字符打印在单独的行上。

    你需要这样的东西:

    with open(tmp.name) as tmp:
        new_division_text = tmp.readlines()
        for line in new_division_text:
            print(line)
    

    注意readlines()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2016-09-27
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 2012-02-01
      • 2015-06-12
      • 1970-01-01
      相关资源
      最近更新 更多