Sys.argv list index out of range [duplicate] - python-3.x

This question already has answers here:
Pycharm and sys.argv arguments
(12 answers)
Closed 1 year ago.
guys. Can someone explain to me why can't I run this script (for converting a jpg into png) in PyCharm? I get an error list index out of range. I have the code and the jpg files in the same directory.
The same error occured when I ran a script to merge some pdf files (the files and the .py script were as well in the same directory).
import sys
import os
from PIL import Image
path = sys.argv[1]
directory = sys.argv[2]
if not os.path.exists(directory):
os.makedirs(directory)
for filename in os.listdir(path):
clean_name = os.path.splitext(filename)[0]
img = Image.open(f'{path}{filename}')
img.save(f'{directory}/{clean_name}.png', 'png')
print('all done!')

I think I have figured it out:
I had to add my args in my Pycharm .py script using the parameters from "modify run configuration" as in this image:
I suppose the same solution works for my image converter script.

Related

How to extract .000 file type in python

How to extract them in python scripts by using shutil or somethings
import os
import shutil
directory = os.path.join(os.getcwd(), "BDP Raw data")
def extract(path,director,check):
if check:
shutil.unpack_archive(path, directory)
if check == False:
shutil.unpack_archive(path, directory,'tar')
def extractzip():
for file in os.listdir(directory):
if file.endswith('.zip'):
file_path = f"{directory}\{file}"
extract(file_path,directory,True)
for file in os.listdir(directory):
if file.startswith('9050') or file.startswith('9070'):
directory_path = f"{directory}\{file}"
for file in os.listdir(directory_path):
extractTo000 = f"{directory}\TestExtract000"
extract_path000 = f"{directory_path}\{file}"
extract(extract_path000,extractTo000,False)
extractzip()
Output should be like this method :
Then I must get this:
I'm not sure that shutil or even py7zr would be able to extract a .000 file.
One of the workarounds is to use Python's built-in module subprocess to unzip this kind of files by 7zip through the Windows command line.
1- CONFIGURATING THE VARIABLE ENVIRONNEMENT
First of all, you need to execute the command below in the command prompt to make sure that your user path environement is pointing to the .exe file of 7-zip. You can also do that manually (see this post).
set PATH=%PATH%;C:\Program Files\7-Zip\"
2- WRITING THE PYTHON FILE
Then, create a .py file in the same directory of your .000 files and write the code below :
from pathlib import Path
import subprocess
path = r'C:\Users\abokey\Desktop\000files'
for file in Path(path).glob('*.000'):
print(file)
subprocess.call(['7z', 'e', file], shell=True)
If you need to extract the files to a specific directory, add the option -o (Set Output Directory):
#make sure to change the output path
subprocess.call(['7z', 'e', file, r'-oC:\Users\abokey\Desktop\000files\output'], shell=True)
Make sure to adapt the code below to match your expectations :
from pathlib import Path
import os
import subprocess
directory = os.path.join(os.getcwd(), "BDP Raw data")
extractTo000 = directory + r'\TestExtract000'
for file in Path(directory).glob('*.000'):
if file.stem.startswith(('9050', '9070')):
subprocess.call(['7z', 'e', file, fr'-o{extractTo000}'], shell=True)
Note : Read full documentation of 7zip here.

Using Path to check if file exists when running script outside of the directory

So I currently use Path to check if a file exists
from pathlib import Path
if Path("main.conf").is_file():
pass
else:
setup_config()
While this works as long as I'm in the directory where I'm running the script, I'd like to make it work whatever directory I'm at and just run the script. I know it doesn't work because it's expecting the main.conf to be in the directory I'm currently in but how do I tell path to only check the in the folder where the script is located in?
You can resolve the absolute path of the script by using sys.argv[0] and then replace the name of that script with the config file to check, eg:
import sys
import pathlib
path = path.Pathlib(sys.argv[0]).resolve()
if path.with_name('main.conf').is_file():
# ...
else:
# ...
Although it seems like you should probably not worry about that check and structure your setup_config so it takes a filename as an argument, eg:
def setup_config(filename):
# use with to open file here
with open(filename) as fin:
# do whatever for config setup
Then wrap your main in a try/except (which'll also cover file not exists/can't open file for other reasons), eg:
path = pathlib.Path(sys.argv[0]).resolve()
try:
setup_config(path.with_name('main.conf'))
except IOError:
pass

python - automatically launch a text file created in the program

I did the search but i couldn't find any help, apologies if i my question is duplicate.
i am writing the code with python 3.6 and in windows environment.in my code, i opened a text file, write the data and close the file.
self.fileName = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()
Instead of the user goes to file path and click to open it, i want to launch the file automatically after python save it.
how do i do that? please help
EDIT:
os.startfile(filepath=self.fileName)
command is working fine, but its opening with default program which is Notepad, how to open the file with specific program, for example, Notepad++
If you know the command line way of doing it, you can use the os module as follows:
import os
self.file = 'file path'
self.log_file = open(self.fileName, 'w')
self.log_file.write('Write results')
self.lof_file.close()
os.system('gedit <file_path>') # for ubuntu, gedit is generally present
For Windows, you can use:
import os
os.startfile('C:\\Users\\RandomUser\\Documents\\test.txt')
Check this answer for more details: https://stackoverflow.com/a/15055133/9332801

Python Invalid syntax - Invalid syntax [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 5 years ago.
I have the following piece of code to pull the names of all files within a particular folder (including all files in it's subfolders):
import sys,os
root = "C:\Users\myName\Box Sync\Projects\Project_Name"
path = os.path.join(root, "Project_Name")
for path, subdirs, files in os.walk(root):
for name in files:
print os.path.join(path, name)
Unfortunately, it throws the following error:
> File "<ipython-input-7-2fff411deea4>", line 8
> print os.path.join(path, name)
> ^ SyntaxError: invalid syntax
I'm trying to execute the script in Jupyter Notebook. I also tried saving it as a .py file and running it through Anaconda prompt but received the same error. Can someone please point out where I'm going wrong? I'm pretty new to Python.
Thanks
in python3, print function needs to be like this :
print(os.path.join(path, name))
For more information on the changes within print function from python 2 to 3, check these links :
print is a function
pep-3105
What is the advantage of the new print function in Python 3.x over the Python 2 print statement?
This is a Python 2 Vs Python 3 issue.
In Python 2, print is used without parenthesis like:
print 42
In Python 3, print is a function and has to be called with parenthesis like:
print(42)

How to convert Balsamiq mockups to text strings txt with Python34 script on Windows XP

I've been trying to run these scripts https://github.com/balsamiq/mockups-strings-extractor within XP. I'm getting errors per this screenshot https://www.dropbox.com/s/rlbqp1iytkwvq3m/Screenshot%202014-05-30%2011.57.48.png
Also I tried CD into my test directory and although a text output file is generated it is empty and I still get these errors https://www.dropbox.com/s/odjfbr97e5i4gnn/Screenshot%202014-05-30%2012.09.31.png
Is anybody running Balsamiq on windows able to make this work ?
1) From the looks of the first error pic you included, you were trying to execute a Windows Shell command inside of a Python Interpreter. If you've still got the window open, type quit() before attempting your command again.
2) Your script was written for Python 2.x. If you're using Python 3.x, you'll need to add parentheses to the print lines in the script file and change urllib to urllib.parse. I made the changes below:
import os
import glob
import re
import urllib.parse
for infile in glob.glob( os.path.join(".", '*.bmml') ):
print("STRINGS FOUND IN " + infile)
print("===========================================================")
f = open (infile,"r")
data = f.read()
p = re.compile("<text>(.*?)</text>")
textStrings = p.findall(data)
print(urllib.parse.unquote('\n'.join(textStrings))+"\n")
f.close()
Hope this helps.

Resources