I am trying to write and read a string onto a temproary file, but when I print each line in the string, it outputs only one character per line (I assume it's because when I run the for loop, it recognizes each "line" of the string as an individual character.
Below is a snippet of my string division_text
if I just perform a print(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
And below is what is being written into the tmp file:
L
o
c
k
e
d
V
e
r
s
o
T
o
k
e
n
.
.
.
My code is below:
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)
The output of print(line)
is the vertical series of characters I wrote above.
The '{}\n'.format(division_text)
doesn't seem to be helping in anything.
I cannot modify the string into a list of lines because then I can't write a list into a file as if it were a .txt file I'd read from. Or could I?
And how does Python/my computer know it is a text file?
CodePudding user response:
read()
reads the entire contents of a file into a single array, that's why when you are iterating through it it prints each character on a separate line.
you need something like:
with open(tmp.name) as tmp:
new_division_text = tmp.readlines()
for line in new_division_text:
print(line)
note the readlines()