Home > Software engineering >  Why is string not being written into tempfile?
Why is string not being written into tempfile?

Time:10-14

I have a script where I create a tempfile and try to write a string onto it and then try to run a for loop within it (while the "with" method is "active").

In the for loop, I try to append specific lines according to a pre-defined pattern, but when I print the lists after appending the lines, not only do the lsist come out empty, but the division_text string was not registered in the temp file to begin with.

I'm basically writing the string onto the temp file and reading it at the same time. Maybe this is the issue.

The 3 prints at the end (one for each list) come out empty, consequently.

Why is the string not being printed into the temp file?

import tempfile    

division_text = 'Hello, world.'
my_list = []

keywords = ['Hello']
pattern = re.compile('|'.join(keywords))

# create temporary .txt file to store string output from web scrape (division_text)
with tempfile.NamedTemporaryFile() as tmp:
    print(tmp.name)
    tmp.write(bytes(division_text, encoding='utf8')) # division_text is a string variable with many lines of text

    for line in tmp:
        print(line)    
        if re.search(pattern, line):
            my_list.append(line)

print(len(token_amount)) # []

If I use tmp.writelines() instead, it gives me the following error:

TypeError: a bytes-like object is required, not 'int'

If I use NamedTemporaryFile(mode='w') instead, and use tmp.write(division_text), it gives me the following error: io.UnsupportedOperation: not readable.

I get the same error when trying:

with tempfile.NamedTemporaryFile(mode = 'r ') as tmp:
    print(tmp.name)
    tmp.write(division_text)
    tmp.seek(0)
    tmp.read()

CodePudding user response:

Here's a workaround just in case the r mode causes issues (no issues here but it may be system dependent)

import tempfile,os
division_text = "12.0"
# create a temporary file, don't delete it when done
tmp_file = tempfile.NamedTemporaryFile(mode = 'w',delete=False)
with tmp_file as tmp:
    print(tmp.name)
    tmp.write(division_text)
# reopen the file for reading
with open(tmp_file.name) as tmp:
    new_division_text=tmp.read()
# remove the file manually
os.remove(tmp_file.name)
# print result
print(new_division)

the idea is to create the temporary file but tell python not to delete it once closed. Then open it again for reading.

In that case, using simple text write and read modes works.

  • Related