Python: How to open json and html files in notepad? - python

Im trying to open json and html files in notepad. I have the following code:
def openFile():
fileName = listbox_1.get(ACTIVE)
if fileName.endswith("json") or fileName.endswith("htm"):
os.system("notepad.exe" + fileName)
elif fileName.endswith("jpeg"):
os.startfile(fileName)
else:
messagebox.showerror(title="Error", message="File is not relevant, please choose one with a directory")
The problem is at the moment all that happens is that a command prompt window flashes up for about a second then disappears. I need for the content of the file to be displayed in notepad.
Using python 3.3 on windows
Thanks in advance

You've missed a space in system call. Proposed fix:
os.system('notepad.exe {}'.format(fileName))

Related

Prevent error console from appearing using .exe file

I have created an exe file using autopy to exe.
At the beginning, I ask the user to enter the file to use using the following code:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
But when the user click on "Cancel" or hit the "X" in the upper right side, an error code appear as you can see on the image
how to stop the code from continue running if the user click one of the two option mentioned above so that the error code will not appear?
I know some questions have already been asked about similar subject but I couldn't adapt them to my case. I hope I have been clear enough
The root cause of the FileNotFoundError is that it cannot find the file with an empty string path, which it will never find that one.
I will elaborate on what #Sagitario has explained. The os.path.exists(filename) used to check if the filename is valid and exists or not:
import os
if os.path.exists(filename):
do_something() # like trying to open a file in this condition.
else:
print(f"{filename} not found, please select other path")
Nevertheless, if your path is empty, it will surely go in an else condition. Instead, you can check the path input that it's not empty and exists.
In addition, the try-except block can help handle the error here. But you also need to solve the main problem of an empty file path somewhere in your code, by using the above if condition to verify the file path.
try:
filename = filedialog.askopenfilename(initialdir="/", title="Select file to convert")
# ... the rest of your code relating the file opening ...
except FileNotFoundError:
print(f"{filename} not found, please select other path")
Just check if the provided path exists with os.path.exists(filename)

Python. trigger .exe(which works as drag and drop with excel file) while in cmd

I have an application that works when I drag an excel file on top on the .exe
Now I want to trigger that application using python(3.8), the ways I tried:
def mycmd():
os.system('cmd /c "\\\\Folder\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\myexe.exe" \\\\Folder\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\myexcel.xlsx')
mycmd()
This way it ignored .xlsx and runs only exe. I tried to play with quotation marks, didn't help, either only .exe boots or I get 'The network name cannot be found.'
Both of the files are stored in a shared network
os.listdir(path) shows both of the files I need.
Thanks for any help in advance.
Ok, I found a solution to my case.
path = "\\\\Folder\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\myexe.exe"
path_input = "\\\\Folder\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\myfile.xlsx"
def myprocess():
os.chdir("\\\\Folder\\F2\\F3\\F4\\F5\\F6\\F7\\F8\\") # i made this because of output of .exe
subprocess.call([f'{path}', f'{path_input}'])
myprocess()

The file with extension .txt doesn't work in Visual Studio Text Editor

When I create a text file in Vscode with an extension .txt, it doesn't work. You will understand better with this image.
You can see in this image, no icon is displayed. When I give extension of any file like .py the icon is diplayed but doesn't work for .txt?
And, when I try to run this python code to read this text file:
f = open("sample.txt","r")
data = f.read()
print(data)
f.close()
It shows this error:
No such file or directory
I have put the file in the same folder still not working
and the same case is with the mp3 files!
Nothing wrong with the icon, .txt or .mp3 have that icon it's okay.
Problem is with your current working directory as you have sample.txt file in Day9 folder so you should try this f = open('Day9/sample.txt').

PDF manipulation with Python

I need to remove the last page of a pdf file. I have multiple pdf files in the same directory. So far I have the next code:
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
def changefile (file):
infile = PdfFileReader(file, "rb")
output = PdfFileWriter()
numpages = infile.getNumPages()
for i in range (numpages -1):
p = infile.getPage(i)
output.addPage(p)
with open(file, 'wb') as f:
output.write(f)
for file in os.listdir("C:\\Users\\Conan\\PycharmProjects\\untitled"):
if file.endswith(".pdf") or file.endswith(".PDF"):
changefile(file)
My script worked while testing it. I need this script for my work. Each day I need to download several e-invoices from our main external supplier. The last page always mentions the conditions of sales and is useless. Unfortunately our supplier left a signature, causing my script not to work properly.
When I am trying to run it on the invoices I receive the following error:
line 1901, in read
raise utils.PdfReadError("Could not find xref table at specified location")
PyPDF2.utils.PdfReadError: Could not find xref table at specified location
I was able to fix it on my Linux laptop by running qpdf invoice.pdf invoice-fix. I can't install QPDF on my work, where Windows is being used.
I suppose this error is triggered by the signature left by our supplier on each PDF file.
Does anyone know how to fix this error? I am looking for an efficient method to fix the issue with a broken PDF file and its signature. There must be something better than opening each PDF file with Adobe and removing the signature manually ...
Automation would be nice, because I daily put multiple invoices in the same directory.
Thanks.
The problem is probably a corrupt PDF file. QPDF is indeed able to work around that. That's why I would recommend using the pikepdf library instead of PyPDF2 in this case. Pikepdf is based on QPDF. First install pikepdf (for example using pip or your package manager) and then try this code:
import pikepdf
import os
def changefile (file):
print("Processing {0}".format(file))
pdf = pikepdf.Pdf.open(file)
lastPageNum = len(pdf.pages)
pdf.pages.remove(p = lastPageNum)
pdf.save(file + '.tmp')
pdf.close()
os.unlink(file)
os.rename(file + '.tmp', file)
for file in os.listdir("C:\\Users\\Conan\\PycharmProjects\\untitled"):
if file.lower().endswith(".pdf"):
changefile(file)
Link to pikepdf docs: https://pikepdf.readthedocs.io/en/latest/
Let me know if that works for you.

beginner-opening explorer to show folder contents

I've been tinkering with Python 3.66 a few days now on windows 7. Making good progress,
but I am totally stuck on how to make windows explorer open with my desired folder contents showing.
I have tried at least 7 different solutions from related questions on here but none seem to work. They all open explorer fine, but never with my Folder_selected
variable.
The explorer bit is the final line of code.
Here is the (badly coded I suspect) source:
#FRenum-v.04
#renumbers a folder of files to 01 onward preserving file extenders.
#Steve Shambles june 2018, my 2nd ever python program
from tkinter import filedialog
from tkinter import *
import os
import os.path
import subprocess
#user selects directory
root = Tk()
root.withdraw() #stop tk window opening
folder_selected = filedialog.askdirectory() #open file requestor
#change dir to folder selected by user,
os.chdir (folder_selected)
#path is now the dir
path=(folder_selected)
# read user selected dir
files = os.listdir(folder_selected)
# inc is counter to keep track of what file we are working on
inc = 1
for file in files:
#store file extender in string file_ext
file_ext = os.path.splitext(file)[1]
# build new filename, starting with a "0" then
#value of inc then add file extender
created_file=("0"+str(inc)+ file_ext)
#if file does not exist rename it
if not os.path.exists(created_file):
os.rename(file,created_file)
#next one please, until done
inc = inc+1 #add to counter
#open explorer showing folder of renamed files
subprocess.Popen(["C:\\Windows\\explorer.exe"])
#these do not work properly, opens in c: or my docs
#subprocess.Popen(["C:\\Windows\\explorer.exe"+ folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected])
#subprocess.Popen(["C:\\Windows\\explorer.exe","folder_selected"])
#todo
#---------
#ignore sub-folders
#confirm requestor
#undo feature
#find out how to stop dos box showing in compiles prg
so, your program is perfect, it's just that for some reason the wrong slashes were being used in the path, which python apparently could handle, but explorer.exe could not.
i ran your program, and printed out folder_selected and i got C:/Users/Michael/Desktop/test. which contains forward slashes, and windows paths use backslashes.
ao i would just replace subprocess.Popen(["C:\\Windows\\explorer.exe"]) to: subprocess.Popen(["C:\\Windows\\explorer.exe", folder_selected.replace('/', '\\')])
which will replace any forward slashes with backslashes, which explorer.exe should be able to handle.
hope this works :)
windows paths also cant have any kind of slash in them, so the user wont have a directory with any / in it, so replace should be fine
This problem caused by the difference between python/linux and windows representing paths.
I printed the folder_selected and get:
C:/Users/name/Documents/Zevel
You need to add the following right after calling askdirectory():
folder_selected = folder_selected.replace('/', '\\')
Making the path readable for windows, and now it looks like:
C:\Users\name\Documents\Zevel
Of course you need call subprocess.Popen(["explorer", folder_selected])
and every thing will work.

Categories