Using Python Click to read a JSON file - python

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()

Related

Pyperclip won't let me copy files if it running, allowing text only

Python Pyperclip won't let me copy files if it running, it only allow text to copy. How can I avoid such problem whenever the script is running, here is what I have done so far... The json file are string and regex file Pyperclip need to listen to
import pyperclip
import json
import time
import re
import sys
import inspect, os
import winreg
from pathlib import Path
import shutil
import pywintypes
import subprocess
import os.path
from os import path
def found_string_text(user_clipboard: str) -> str:
"""Returns name of found string_text in user_clipboard"""
# open matches
with open(resource_path("regex_match.json")) as json_file:
regex_addresses = json.load(json_file)
# go through matches, check if any regex matches user_clipboard
for string_text_name, string_text_address in regex_addresses.items():
if bool(re.search(string_text_address, user_clipboard)):
return string_text_name
return None # no string_text found
def replace_clipboard(found_string_text: str) -> str:
with open(resource_path("addresses.json")) as json_file:
master_addresses = json.load(json_file)
if master_addresses[found_string_text] != "ignore" and type(master_addresses[found_string_text] is str):
pyperclip.copy(master_addresses[found_string_text])
#print(f"Replaced:{master_addresses[found_string_text]}")
def main():
#print("Watching")
while True:
try:
time.sleep(0.5)
user_clipboard = str(pyperclip.paste())
# check if found
found_string_text_name = found_string_text(user_clipboard)
if found_string_text_name is not None:
# if so replace
#print(f"Found:{found_string_text_name}")
replace_clipboard(found_string_text_name)
except pyperclip.PyperclipWindowsException:
pass
except KeyboardInterrupt:
#print("Goodbye.")
sys.exit(0)
def checkifexist_file():
if os.path.exists('myfolder\\file.txt'):
main()
else:
rev()
main()
if __name__ == '__main__':
checkifexist_file()
enter code here
Please genius help me, when the script run it runs fine but won't allow user to copy other content. E.g like files, it only allow user copy text only.
I later find other alternative Lib by using win32clipboard module from pywin32 Lib, here is it
def get_clipboard():
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
return data
def set_clipboard(text):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text, win32clipboard.CF_TEXT )
#win32clipboard.SetClipboard(text.encode('utf-8'),win32clipboard.CF_TEXT)
#win32clipboard.SetClipboard(unicode(text),win32clipboard.CF_UNICODETEXT)
win32clipboard.CloseClipboard()
def main():
try:
dataR = get_clipboard()
if type((dataR) is str):
for key in addr:
findstring_text = re.search(key,dataR)
if (findstring_text):
set_clipboard(addr[key])
except pywintypes.error as e:
pass
except TypeError:
win32clipboard.CloseClipboard()
It really work well.. Thanks

Prompt toolkit write multiline input to file and close the prompt

I would like to make some form of terminal editor for text-based files.
When started, it prints the current content of the file and makes it possible for user to edit in (multiline input). On press of CTRL + E, it should write that multiline input into specific file and close the prompt.
I have tried using this code, but it doesn't seem to work.
from prompt_toolkit import prompt, PromptSession
from prompt_toolkit.lexers import PygmentsLexer
from pygments.lexers.python import PythonLexer
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
file_path = 'output.txt'
file = open(file_path, 'r')
content = file.read()
new_content = None
session = PromptSession()
bindings = KeyBindings()
#bindings.add('c-e')
def _(event):
global new_content
global file_path
file = open(file_path, 'w')
file.write(new_content)
session.app.exit()
def show_prompt():
global new_content
global session
bottom_toolbar = HTML('<b><style background-color="white" color="green">Input</style></b>')
lexer = PygmentsLexer(PythonLexer)
new_content = session.prompt('\n',
default=content,
lexer=lexer,
multiline=True,
bottom_toolbar=bottom_toolbar,
key_bindings=bindings)
# Start of the program
if __name__ == '__main__':
show_prompt()

Python - wget does not work with storing print in file

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())

python reading header from word docx

I am trying to read a header from a word document using python-docx and watchdog.
What I am doing is, whenever a new file is created or modified the script reads the file and get the contents in the header, but I am getting an
docx.opc.exceptions.PackageNotFoundError: Package not found at 'Test6.docx'
error and I tried everything including opening it as a stream but nothing has worked, and yes the document is populated.
For reference, this is my code.
**main.py**
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import watchdog.observers
import watchdog.events
import os
import re
import xml.dom.minidom
import zipfile
from docx import Document
class Watcher:
DIRECTORY_TO_WATCH = "/path/to/my/directory"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler,path='C:/Users/abdsak11/OneDrive - Lärande', recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
print ("Error")
self.observer.join()
class Handler(FileSystemEventHandler):
#staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
# Take any action here when a file is first created.
path = event.src_path
extenstion = '.docx'
base = os.path.basename(path)
if extenstion in path:
print ("Received created event - %s." % event.src_path)
time.sleep(10)
print(base)
doc = Document(base)
print(doc)
section = doc.sections[0]
header = section.header
print (header)
elif event.event_type == 'modified':
# Taken any action here when a file is modified.
path = event.src_path
extenstion = '.docx'
base = os.path.basename(path)
if extenstion in base:
print ("Received modified event - %s." % event.src_path)
time.sleep(10)
print(base)
doc = Document(base)
print(doc)
section = doc.sections[0]
header = section.header
print (header)
if __name__ == '__main__':
w = Watcher()
w.run()
Edit:
Tried to change the extension from doc to docx and that worked but is there anyway to open docx because thats what i am finding.
another thing. When opening the ".doc" file and trying to read the header all i am getting is
<docx.document.Document object at 0x03195488>
<docx.section._Header object at 0x0319C088>
and what i am trying to do is to extract the text from the header
You are trying to print the object itself, however you should access its property:
...
doc = Document(base)
section = doc.sections[0]
header = section.header
print(header.paragraphs[0].text)
according to https://python-docx.readthedocs.io/en/latest/user/hdrftr.html)
UPDATE
As I played with python-docx package, it turned out that PackageNotFoundError is very generic as it can occur simply because file is not accessible by some reason - not exist, not found or due to permissions, as well as if file is empty or corrupted. For example, in case of watchdog, it may very well happen that after triggering "created" event and before creating Document file can be renamed, deleted, etc. And for some reason you make this situation more probable by waiting 10 seconds before creating Document? So, try checking if file exists before:
if not os.path.exists(base):
raise OSError('{}: file does not exist!'.format(base))
doc = Document(base)
UPDATE2
Note also, that this may happen when opening program creates some lock file based on file name, e.g. running your code on linux and opening the file with libreoffice causes
PackageNotFoundError: Package not found at '.~lock.xxx.docx#'
because this file is not docx file! So you should update your filtering condition with
if path.endswith(extenstion):
...

Flask - How to download a filename with a . dot prefix?

I have a flask app and am trying to set up a download where the file that is downloaded starts with a "." (dot, or period). The code is listed below, but I have tried several methods, each simply removes the "dot" at the beginning. I feel like this should be simple, but I am stuck. Any help would be appreciated.
Thanks
#app.route('/.blah.auth', methods=['GET'])
def downloadBlahAuth(roleLevel = app.config["PAGE_ROLE_LEVELS"][".blah.auth"]):
"""
filePath = os.path.join(app.config["DOWNLOADS_FOLDER"], ".blah.auth");
theFile = open(filePath, "r")
fileText = theFile.read()
theFile.close()
strIO = StringIO.StringIO()
strIO.write(fileText)
strIO.seek(0)
return send_file(strIO, attachment_filename=".blah.auth", as_attachment=True)
"""
fileName = ".blah.auth"
return send_from_directory(directory=app.config["DOWNLOADS_FOLDER"], filename=fileName)

Categories