Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - writing and reading from a temporary file

I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data. I am not sure how to find and open the temp file so I can read it. My code:

with tempfile.TemporaryFile() as tmp:     lines = open(file1).readlines()     tmp.writelines(lines[2:-1])  dependencyList = []  for line in tmp:     groupId = textwrap.dedent(line.split(':')[0])     artifactId = line.split(':')[1]     version = line.split(':')[3]     scope = str.strip(line.split(':')[4])     dependencyObject = depenObj(groupId, artifactId, version, scope)     dependencyList.append(dependencyObject) tmp.close() 

Essentially I just want to make a middleman temporary document to protect against accidentally overwriting a file.

like image 865
fractalflame Avatar asked Oct 11 '16 18:10

fractalflame


People also ask

How do I write a Tempfile?

If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.

When should you use Tempfile?

In my view, you should use tempfile when you need to create a file but don't care about its name. You can have the file deleted automatically when you're done or saved, if you wish. It can also be visible to other programs or not. Save this answer.

Where temporary files are stored python?

gettempdir() This function returns name of directory to store temporary files. This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp.


1 Answers

As per the docs, the file is deleted when the TemporaryFile is closed and that happens when you exit the with clause. So... don't exit the with clause. Rewind the file and do your work in the with.

with tempfile.TemporaryFile() as tmp:     lines = open(file1).readlines()     tmp.writelines(lines[2:-1])     tmp.seek(0)      for line in tmp:         groupId = textwrap.dedent(line.split(':')[0])         artifactId = line.split(':')[1]         version = line.split(':')[3]         scope = str.strip(line.split(':')[4])         dependencyObject = depenObj(groupId, artifactId, version, scope)         dependencyList.append(dependencyObject) 
like image 117
tdelaney Avatar answered Sep 28 '22 15:09

tdelaney