How to create and read from a temporary file in Python?

0 votes

Hi all, my question is pretty simple. 

I wanted to know if there was any way which could help me write to a temporary file and later implement his in a command. So, this would later be able to be closed or removed as per requirement.

And that command should be executable by the user at all times. Consider this example:

random_command/tmp/a-temp-file. How can this be done?

Check out the code for a bit of better clarity (If it helps!)

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()

Appreciate the help!

Jan 29 in Python by Anirudh
• 2,070 points
100 views

1 answer to this question.

0 votes

Hi, there is a very simple solution to the asked question. 

Well, if you actually are looking for a temp file which has a particular name, then you will have to use a built-in function for this. 

The built-in function is called the NamedTemporaryFile function. I am sure you would already be aware of this or you have used this in the past. I tend to do this myself too, haha!

Then, later what you can do is to make use of the temp.name and this should directly solve your issues.

For further clarification, I suggest you check out the official Python documentation for the tempfile and you should be good to go.

Hope this helped!

answered Jan 29 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

How to read numbers from file in Python?

Assuming you don't have extraneous whitespace: with open('file') ...READ MORE

answered Apr 16 in Python by SDeb
• 13,210 points
106 views
0 votes
1 answer

How to read data from a text file using Python?

Refer to the below example where the ...READ MORE

answered May 12 in Python by Sushma
72 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 405 views
+4 votes
6 answers
0 votes
1 answer

How to use read a WSDL file from the file system using Python suds?

Hi, good question. It is a very simple ...READ MORE

answered Jan 21 in Python by Nymeria
• 3,520 points
752 views
0 votes
1 answer

How can I read numbers in Python from a custom file?

Hi, good question. Let us first assume that ...READ MORE

answered Feb 6 in Python by Nymeria
• 3,520 points
87 views