I have this file:
import wget
import sys
import datetime
class Printer(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for file in self.files:
file.write(obj)
file.flush()
def flush(self):
for file in self.files:
file.flush()
f = open(f"{__file__}-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.log", 'w')
sys.stdout = Printer(sys.stdout, f)
url='https://www.w3.org/TR/PNG/iso_8859-1.txt'
wget.download(url)
#Your print statements below
print("Hello world!")
My above code does not work. It does not download the file. The question is to make the download work while storing the print logs in the log file.
The wget python package downloads content of a URL in a file. Below is a working example:
import wget
url = 'https://www.w3.org/TR/PNG/iso_8859-1.txt'
filename = wget.download(url)
with open(filename, 'r') as f:
print(f.read())
Related
I have a module that can save and load data and it only takes up one file. How do I make it installable with pip? The code is
import subprocess
def save(stuffToStore, title):
f = open(title + '.sv', 'w')
f.write(stuffToStore)
f.close()
def load(title):
f = open(title + '.sv', 'r')
contents = f.read()
f.close()
return(contents)
I would also like to include a readme and a MIT license. And I would also like to post it on GitHub.
I am new to python and I am trying to read in a JSON file, that for now I can just write out to a new file without any changes. I have been attempting to use the python package Click to do this but keep running into errors.
I'm sure this is relatively basic but any help would be appreciated. The latest version of the code I've tried is below.
import json
import os
import click
def dazprops():
"""Read Daz3D property File"""
path = click.prompt('Please specify a location for the Daz3D Properties File')
path = os.path.realpath(path)
#dir_name = os.path.dirname(path)
print(path)
dazpropsf = open('path')
print(dazpropsf)
if __name__ == '__main__':
dazprops()
Something like this could give you an idea how to achieve that using click:
import click
def read_file(fin):
content = None
with open(fin, "r") as f_in:
content = f_in.read()
return content
def write_file(fout, content):
try:
print("Writing file...")
with open(fout, "w") as f_out:
f_out.write(content)
print(f"File created: {fout}")
except IOError as e:
print(f"Couldn't write a file at {fout}. Error: {e}")
#click.command()
#click.argument('fin', type=click.Path(exists=True))
#click.argument('fout', type=click.Path())
def init(fin, fout):
"""
FINT is an input filepath
FOUT is an output filepath
"""
content = read_file(fin)
if content:
write_file(fout, content)
if __name__ == "__main__":
init()
I have a function similar to this:
def open_tmp():
tmp = mktemp()
copy('file.txt', tmp)
return open(tmp, 'rt')
And I would like to remove automatically the created temporal file when the file will close, for example:
file = open_tmp()
# Do something with file
file.close() # I want to remove the temporal file here
Is it possible? I thought to create a subclass of BaseIO and rewrite the close() function, but I think it is too much work because I would have to rewrite all the BaseIO methods.
You can try this code snippet. As per security concern I recommended to use tempfile instead of your code.
import os
import tempfile
new_file, file_path = tempfile.mkstemp()
try:
with os.fdopen(new_file, 'w') as temp_file:
# Do something with file
temp_file.write('write some dumy text in file')
finally:
os.remove(file_path)
I've found the solution:
import os
import tempfile
def open_tmp():
tmp = tempfile.mkstemp()
copy('file.txt', tmp) # This copy the file.txt to tmp
file = open(tmp, 'rt')
old_close = file.close
def close():
old_close()
os.remove(tmp)
file.close = close
return file
I have the following code:
import os
import sys
import tempfile
import subprocess
with tempfile.NamedTemporaryFile('w+') as f:
if sys.platform == 'linux':
subprocess.call('vim', f.name)
elif sys.platform == 'nt':
os.system(f.name)
It opens foobar.txt using either vim on Linux, or the default editor on Windows. On Linux it works fine: tempfile.NamedTemporaryFile() creates a temporary file and vim opens it. On Windows, however, the system says:
The process cannot access the file because it is being used by another process.
I guess that's because the script is currently using the file.
Why does it work on Linux, and how do I get it to work on Windows?
I've run into this problem before. My problem was that I had to write to a file and then use that file's name as an argument in a command.
The reason this works in Linux is that, as #PM 2Ring said in the comments, Linux allows multiple processes to write to the same file, but Windows does not.
There are two approaches to tackle this.
One is to create a temporary directory and create a file in that directory.
# Python 2 and 3
import os
import tempfile
temp_dir = tempfile.mkdtemp()
try:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
try:
do_stuff(temp_file) # In this case, open the file in an editor.
finally:
os.remove(file_name)
finally:
os.rmdir(temp_dir)
# Python 3 only
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
temp_file = os.path.join(temp_dir, 'file.txt')
with open(temp_file, 'w') as f:
pass # Create the file, or optionally write to it.
do_stuff(temp_file)
# with tempfile.TemporaryDirectory(): automatically deletes temp_file
Another approach is to create the temporary file with delete=False so that when you close it, it isn't deleted, and then delete it manually later.
# Python 2 and 3
import os
import tempfile
fp = tempfile.NamedTemporaryFile(suffix='.txt', delete=False)
try:
fp.close()
do_stuff(fp.name)
finally:
os.remove(fp.name)
Here is a little context manager that can make files:
import os
import tempfile
_text_type = type(u'')
class ClosedTemporaryFile(object):
__slots__ = ('name',)
def __init__(self, data=b'', suffix='', prefix='tmp', dir=None):
fp = tempfile.mkstemp(suffix, prefix, dir, isinstance(data, _text_type))
self.name = fp.name
if data:
try:
fp.write(data)
except:
fp.close()
self.delete()
raise
fp.close()
def exists(self):
return os.path.isfile(self.name)
def delete(self):
try:
os.remove(self.name)
except OSError:
pass
def open(self, *args, **kwargs):
return open(self.name, *args, **kwargs)
def __enter__(self):
return self.name
def __exit__(self, exc_type, exc_val, exc_tb):
self.delete()
def __del__(self):
self.delete()
Usage:
with ClosedTemporaryFile(suffix='.txt') as temp_file:
do_stuff(temp_file)
I have a txt file containing hex of an exe. I read that file in python, but failed to run that .exe file.
any kind of help will be appriciated...
thanx
import binascii
def getExeFile():
file1=input("Enter an exe file name(path):")
with open(file1, 'rb') as f:
content1 = f.read()
bucket1=open("f1.txt", 'w')
bucket1.write(str(binascii.hexlify(content1)))
print(binascii .hexlify(content1))
bucket1.close()
def getNonExeFile():
file2=input("Enter a non-exe file name(path):")
with open(file2, 'rb') as f:
content2 = f.read()
bucket2=open("f2.txt", 'w')
bucket2.write(str(binascii.hexlify(content2)))
print(binascii .hexlify(content2))
bucket2.close()
getExeFile()
getNonExeFile()
print("End")
Dump it to a temporary file; Change it's permissions so it's executable and run it in a subprocess
Example:
from os import chown
from subprocess import check_call
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(delete=False) as f:
f.write(get_hex_from_file("mydata.dat"))
chown(f.name, 0755)
check_call(f.name)
Of course I'm making the assumption here that you are doing this on some kind of UNIX machine and that "EXE" in this case means some kind of ELF/A.OUT/COFF executable! -- Nevertheless; same principles and code (with some tweaking) would probably work on other paltforms; e.g: Windows.
See:
tempfile.NamedTemporaryFile
subprocess.check_call
os.chown
Python 3.4:
This is my code that create a simple txt file having hex of and exe and a txt file.
Now I want my program to take that hex file and run the exe file and open the txt file.
import binascii
def getExeFile():
file1=input("Enter an exe file name(path):")
with open(file1, 'rb') as f:
content1 = f.read()
bucket1=open("f1.txt", 'w')
bucket1.write(str(binascii.hexlify(content1)))
bucket1.close()
def getNonExeFile():
file2=input("Enter a non-exe file name(path):")
with open(file2, 'rb') as f:
content2 = f.read()
bucket2=open("f2.txt", 'w')
bucket2.write(str(binascii.hexlify(content2)))
bucket2.close()
getExeFile()
getNonExeFile()
print("End")
Thanx...!