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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With