How can I create a tmp file in Python? - python

I have this function that references the path of a file:
some_obj.file_name(FILE_PATH)
where FILE_PATH is a string of the path of a file, i.e. H:/path/FILE_NAME.ext
I want to create a file FILE_NAME.ext inside my python script with the content of a string:
some_string = 'this is some content'
How to go about this? The Python script will be placed inside a Linux box.

I think you're looking for a tempfile.NamedTemporaryFile.
import tempfile
with tempfile.NamedTemporaryFile() as tmp:
print(tmp.name)
tmp.write(...)
But:
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
If that is a concern for you:
import os, tempfile
tmp = tempfile.NamedTemporaryFile(delete=False)
try:
print(tmp.name)
tmp.write(...)
finally:
tmp.close()
os.unlink(tmp.name)

There is a tempfile module for python, but a simple file creation also does the trick:
new_file = open("path/to/FILE_NAME.ext", "w")
Now you can write to it using the write method:
new_file.write('this is some content')
With the tempfile module this might look like this:
import tempfile
new_file, filename = tempfile.mkstemp()
print(filename)
os.write(new_file, "this is some content")
os.close(new_file)
With mkstemp you are responsible for deleting the file after you are done with it. With other arguments, you can influence the directory and name of the file.
UPDATE
As rightfully pointed out by Emmet Speer, there are security considerations when using mkstemp, as the client code is responsible for closing/cleaning up the created file. A better way to handle it is the following snippet (as taken from the link):
import os
import tempfile
fd, path = tempfile.mkstemp()
try:
with os.fdopen(fd, 'w') as tmp:
# do stuff with temp file
tmp.write('stuff')
finally:
os.remove(path)
The os.fdopen wraps the file descriptor in a Python file object, that closes automatically when the with exits. The call to os.remove deletes the file when no longer needed.

Related

how can i adding custom path for saving the zip_file

I am creating a zip file using the zipfile module. It works like a charm. but that'sĀ file, saved in the executed script place.
my script path is a:
[b]c:/User/Administrator/[/b]script.py
and the zipfile saved in:
[b]c:/User/Administrator/[/b]backup.zip
but I want, [b]creating a zipfile, in another path[/b], like this:
[b]d:/backups/[/b]backup.zip
my code like this:
import zipfile
zip_file = zipfile.ZipFile("backup.zip", 'w')
with zip_file:
for file in filePaths:
zip_file.write(file)
my question is a how can I adding custom path for saving the zip_file. because I have not an enough space in C:
tnx a lot.
Give the path you want to ZipFile function.
When you give only the name of the file, it will save the file in the current directory which the program is running.
Do this instead:
import zipfile
# For example you want to save it in drive 'D'
path = "D:\\PathToYourDir\\backup.zip"
zip_file = zipfile.ZipFile(path, 'w')
with zip_file:
for file in filePaths:
zip_file.write(file)

Write to any users desktop in Python

Im new to Python so apologies if this is a basic question.
I have successfully created an exe file that writes to my specific desktop directory, but I am struggling to find a way to write to any users desktop directory.
The idea being my exe file can be copied onto any user profile and work the same.
Here is my code:
file = open('C:\\Users\\user\\Desktop\\PC info.txt','w')
Could somebody help me adjust my code to work on any users desktop. Thank you in advance
You can get the username with the os module:
import os
username = os.getlogin() # Fetch username
file = open(f'C:\\Users\\{username}\\Desktop\\PC info.txt','w')
file.write('Hello desktop')
file.close()
You could use os.getlogin with an f-string to insert the username to the file path:
import os
with open(fr'C:\Users\{os.getlogin()}\Desktop\PC info.txt', 'w') as f:
# do something with f
But, a much better cleaner way nowadays would be to use pathlib:
import pathlib
with open(pathlib.Path.home() / "Desktop/PC info.txt", "w"):
# do something with f
Also, it's always advisable to use a context manager (with open(...) as f) to handle files, so that the filehandler gets closed even if an exception occurs.
If you are using Python3.5+, you can use the following to get the path to the current user's home directory:
import os
import sys
from pathlib import Path
def main():
home = str(Path.home())
path = os.path.join(home, "filename.txt")
with open(path, "w") as f:
f.write("HelloWorld")
if __name__ == '__main__':
main()
Is this what you are looking for?
username = "MrShaun"
filename = "C:\\Users\\{0}\\Desktop\\PC info.txt".format(username)
file = open(filename, 'w')
In this example, filename would be: "C:\Users\MrShaun\Desktop\PC info.txt"
Obviously, you would probably want to build a structure around it, for example asking the user for input of a username and assigning that to the variable username.
Read more about formatting strings in Python here

python import a module with source code in temporary file

import tempfile
tmp = tempfile.NamedTemporaryFile(delete=True)
try:
# do stuff with temp
tmp.write(b'def fun():\n\tprint("hello world!")\n')
if __name__ == '__main__':
func = __import__(tmp.name)
func.fun()
finally:
tmp.close() # deletes the file
So I want to create a temporary file, add some source code to it and then import the module and call the function, but I always run into this error:
ModuleNotFoundError: No module named '/var/folders/3w/yyp887lx4018h9s5sr0bwhkw0000gn/T/tmp84bk0bic'
It doesn't seem to find the module of the temporary file. How do I solve this?
There are a few problems with your code:
Your filename does not end with .py, but Python modules are expected to. You can fix this by setting suffix='.py' in NamedTemporaryFile().
__import__() is not the right way to load a module from a full path. See here: How to import a module given the full path?
You do not flush after writing and before importing, so even if Python does find the file, it may well be empty. Add tmp.flush() after writing to fix this.
Importing can only be done from certain directories which are part of the PYTHON_PATH. You can extend that. Then you will have to use __import__() with a module name (not a path in the file system). You will have to deal with the suffix for the temp file.
I implemented a simple version using the local directory for the temp module file and a version using a proper tempfile:
#!/usr/bin/env python3
import sys
import os
import tempfile
SCRIPT = '''\
def fun():
print("hello world!")
'''
# simple version using the local directory:
with open('bla.py', 'w') as tmp_module_file:
tmp_module_file.write(SCRIPT)
import bla
bla.fun()
# version using the tempfile module:
tmpfile = tempfile.NamedTemporaryFile(suffix='.py', delete=True)
try:
tmpfile.write(SCRIPT.encode('utf8'))
tmpfile.flush()
tmpmodule_path, tmpmodule_file_name = os.path.split(tmpfile.name)
tmpmodule_name = tmpmodule_file_name[:-3] # strip off the '.py'
sys.path.append(tmpmodule_path)
tmpmodule = __import__(tmpmodule_name)
finally:
tmpfile.close()
tmpmodule.fun()

Permission Denied To Write To My Temporary File

I am attempting to create and write to a temporary file on Windows OS using Python. I have used the Python module tempfile to create a temporary file.
But when I go to write that temporary file I get an error Permission Denied. Am I not allowed to write to temporary files?! Am I doing something wrong? If I want to create and write to a temporary file how should should I do it in Python? I want to create a temporary file in the temp directory for security purposes and not locally (in the dir the .exe is executing).
IOError: [Errno 13] Permission denied: 'c:\\users\\blah~1\\appdata\\local\\temp\\tmpiwz8qw'
temp = tempfile.NamedTemporaryFile().name
f = open(temp, 'w') # error occurs on this line
NamedTemporaryFile actually creates and opens the file for you, there's no need for you to open it again for writing.
In fact, the Python docs state:
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
That's why you're getting your permission error. What you're probably after is something like:
f = tempfile.NamedTemporaryFile(mode='w') # open file
temp = f.name # get name (if needed)
Use the delete parameter as below:
tmpf = NamedTemporaryFile(delete=False)
But then you need to manually delete the temporary file once you are done with it.
tmpf.close()
os.unlink(tmpf.name)
Reference for bug: https://github.com/bravoserver/bravo/issues/111
regards,
Vidyesh
Consider using os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) instead. It's reliable, cross-platform, and the only caveat is that it doesn't work on FAT partitions.
NamedTemporaryFile has a number of issues, not the least of which is that it can fail to create files because of a permission error, fail to detect the permission error, and then loop millions of times, hanging your program and your filesystem.
The following custom implementation of named temporary file is expanded on the original answer by Erik Aronesty:
import os
import tempfile
class CustomNamedTemporaryFile:
"""
This custom implementation is needed because of the following limitation of tempfile.NamedTemporaryFile:
> Whether the name can be used to open the file a second time, while the named temporary file is still open,
> varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).
"""
def __init__(self, mode='wb', delete=True):
self._mode = mode
self._delete = delete
def __enter__(self):
# Generate a random temporary file name
file_name = os.path.join(tempfile.gettempdir(), os.urandom(24).hex())
# Ensure the file is created
open(file_name, "x").close()
# Open the file in the given mode
self._tempFile = open(file_name, self._mode)
return self._tempFile
def __exit__(self, exc_type, exc_val, exc_tb):
self._tempFile.close()
if self._delete:
os.remove(self._tempFile.name)
This issue might be more complex than many of you think. Anyway this was my solution:
Make use of atexit module
def delete_files(files):
for file in files:
file.close()
os.unlink(file.name)
Make NamedTemporaryFile delete=False
temp_files = []
result_file = NamedTemporaryFile(dir=tmp_path(), suffix=".xlsx", delete=False)
self.temp_files.append(result_file)
Register delete_files as a clean up function
atexit.register(delete_files, temp_files)
tempfile.NamedTemporaryFile() :
It creates and opens a temporary file for you.
f = open(temp, 'w') :
You are again going to open the file which is already open and that's why you are getting Permission Denied error.
If you really wants to open the file again then you first need to close it which will look something like this-
temp= tempfile.NamedTemporaryFile()
temp.close()
f = open(temp.name, 'w')
Permission was denied because the file is Open during line 2 of your code.
close it with f.close() first then you can start writing on your tempfile

Creating a python file in a local directory

Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it?
using python 3.3
To find the the directory that the script is in:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
use open:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with statement:
with open("folder_name/myfile.txt","w") as f:
#do something with f

Categories

Resources