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, 2019 in Python by Anirudh
• 2,090 points
2,057 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, 2019 by Nymeria
• 3,560 points

Related Questions In Python

–1 vote
2 answers
0 votes
0 answers
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, 2019 in Python by SDeb
• 13,300 points
7,498 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 13, 2019 in Python by Sushma
1,511 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,441 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,077 views
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, 2019 in Python by Nymeria
• 3,560 points
8,317 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, 2019 in Python by Nymeria
• 3,560 points
1,133 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP