how to use "code ." command in python script - python

I have made a piece of code to automate making a new project. I ahve mangaged to create the file in a location I like, create the file and create a test python file. How would I open that file in vs code?
import subprocess,os,time
projectName = input("What is the name of the project?\n")
filename = "test"
fileEx = '.py'
os.chdir('../')
os.chdir('../')
os.chdir('../')
os.chdir('.\Documents\ ')
os.chdir('.\programs\ ')
project = subprocess.Popen(["powershell","md",projectName])
file = filename + fileEx
fileLoctaion = os.getcwd() + file
d = os.getcwd() + f'\{projectName}\ '
time.sleep(1)
os.chdir(d)
with open(file, 'w') as fp:
pass

You could try the following:
import os
os.system("code NAMEOFFILE.py") ## the "code" command is the command used to open a file with vsc in a command line interface.
You can do the same thing with subprocess:
import subprocess
subprocess.getoutput("code NAMEOFFILE.py")

Related

How to run a Python script in a different directory accessing file of current directory(see example explaining issue)

file1 -> "/1/2/3/summer/mango.txt"
file2 -> "/1/2/3/winter/dates.txt"
Script -> "/1/Python/fruit.py"
Problem 1) I am unable to execute fruit.py in summer/winter folder. While it works properly, if i kept the script in a summer/winter folder.
Problem 2) The script required to access *.txt file of directory where i execute it. Here in example, mango.txt or dates.txt.
Here is my code,
#! /usr/bin/python
import glob
import os
import csv
....
for name in glob.glob("*.txt"):
target_path_1 = os.path.join(os.path.dirname(__file__), name)
txt_file = open(target_path_1,"r")
ipaddr = raw_input("Enter IP address: ")
fname = (name.replace(".txt","_"))+(ipaddr+".csv")
target_path_2 = os.path.join(os.path.dirname(__file__), fname)
csv_file = open(target_path_2,"w")
writer = csv.writer(csv_file)
....
csv_file.close()
txt_file.close()
You have both directories accessible like this:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
my_dir = os.getcwd()
print(script_dir, my_dir)
Result
~ $ python temp/test.py
/home/roman/temp /home/roman

Can you pass a variable to the import function of python?

i create a python file via the "with open()" method and now i would like to import the file but the filename should be variable.
filename = "Test"
with open(filename + ".py", "w+") as file:
file.write("def main():\n\tpass")
Now at a other line in the skript i would like to import the python script called like filename. But you cant do something like:
import filename
because then python searches for a python script called "filename". but in this example it should import "Test.py". Any suggestions?
You want the built in import function
new_module = __import__(modulename)
so...
filename = "Test"
with open(filename + ".py", "w+") as file:
file.write("def main():\n\tpass")
new_module = __import__(filename)
Visit https://docs.python.org/3/library/functions.html#__import__

how to make script in python run at startup after converting it to exe by py installer

I want to make my script run on startup automatically after converting it to EXE by pyinstaller tool ,
*once clicking on SPEED.EXE 'name of program' ,It copies itself to particular path on computer then makes a bat file in startup folder 'it contains code to start SPPED.EXE'
but my problem that bat file doesnot run on start *
import os
import ftplib
import sys
import shutil
import getpass
##################copy script into startup#######################
def copy_script():
USER_NAME = getpass.getuser()
src=sys.argv[0]
dst = r'C:\Users\%s\AppData' % USER_NAME
shutil.copy2(src,dst)
dst='C:\Users\\"%s"\AppData\SPEED.exe' % USER_NAME ######name of script after making EXE
add_to_startup(USER_NAME,file_path=dst)
return None
######################################make a bat file to run on startup######
def add_to_startup(USER_NAME,file_path):
if file_path == "":
file_path = os.path.dirname(os.path.realpath(__file__))
bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
with open(bat_path + '\\' + "open.bat", "w") as bat_file:
bat_file.write(r'#echo off'+ os.linesep) ## to hide console batch file when it run
bat_file.write(r'start "" %s' % file_path)
if __name__=='__main__':
copy_script()
start() ##it is function that i make it
thanks,I could solve my problem.
instead of creating a bat file in startup file " I delete add_to_startup method " ,I used registry method
import winreg;
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0,
winreg.KEY_SET_VALUE); winreg.SetValueEx(key, 'speed', 0,
winreg.REG_SZ,'file_path'); # file_path is path of file after coping it
the error "fatal error failed to execute script SPEED " is result of the method shutil.copy2(src,dst) can't copy the same source to same destination at startup so I make exception
try:
shutil.copy2(src,dst)
except:
pass

copy content of file to another file using python script

i have this python script that open a file dialog and select a text file than copy its content to another file.
when i open the second file it still empty
can anyone help me to solve this problem ?
OPenDirectory.py
#!/usr/bin/python
import Tkinter
import tkFileDialog
''''Open txt files in the selected path '''
def OpenRead():
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = 'C:\Users\LT GM\Downloads', filetypes=[('text files', ' TXT ')])
readingFile = in_path.read()
writeFile = open ('copiedFile.txt', 'w')
writeFile.write(readingFile)
print " we'r done!!"
in_path.close()
writeFile.close()
if __name__== "__main__":
OpenRead()
You can use shutil.copyfile, there is no need to open or read the file.
from shutil import copyfile
copyfile("source","dest")
So for your code:
def OpenRead():
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfile(initialdir = 'C:\Users\LT GM\Downloads', filetypes=[('text files', ' TXT ')])
copyfile(in_path.name, 'copiedFile.txt')
print " we'r done!!"
if __name__== "__main__":
OpenRead()
The file is also going to be copied to you pwd so if you want it save somewhere in particular you need to pass the full path.
Line by line way of copying from file to file:
#!/usr/bin/python
from os import listdir
from os.path import isfile, join
def readWrite():
mypath = 'D:\\'
files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
for file in files:
if file.split('.')[1] == 'txt':
outputFileName = 'out-' + file
with open(mypath+outputFileName, 'w') as w:
with open(mypath+file) as f:
for l in f:
print l
w.write(l)
if __name__== "__main__":
readWrite()
UPDATE:
updated the code above, so it reads all the txt files in a specified directory and copies them into other files. You can play with directories how you like. I also added a "print l" which will print the contents of the incoming file.
readingFile = in_path.read()
reads the contents of the file and puts it in variable readingFile
suppose the contents of the file is,say, hello the value of readingFile will be hello
destinationFile = readingFile, '.txt'
destinationFile is a tuple with values '<'contents of file'>','.txt'
instead use destinationFile = readingFile+'.txt'
this will work. but the end result would not be what you are expecting.the result would be a file with name as contents of the reading file with contents also the same. better specify a file name in destinationFile like destinationFile = 'destfile.txt'
Why don't you just use os, and the shell copy command.
import os
start= '~/user/file'
dest= '~/user/folder1/file'
os.system('cp %s %s' %(start,dest))

how to open a file by user input in python

I am (trying) to write a tool that will open a file based on user input.
I want to eventually write the results of the script into a file and store it into the same directory as the input file.
I currently have this
from Bio import SeqIO
import os, glob
var = raw_input("what is the path to the file (you can drag and drop):")
fname=var.rsplit("/")[-1]
fpath = "/".join(var.rsplit("/")[:-1])
os.chdir(fpath)
#print os.getcwd()
#print fname
#for files in glob.glob("*"):
# print files
with open(fname, "rU") as f:
for line in f:
print line
I do not understand why I cannot open the file. Both the "os.getcwd" and the "glob.glob" part show that I successfully moved to the users directory. In addition, the file is in the correct folder. However, I cannot open the file...
any suggestions would be appreciated
Try this to open the file and get the path to the file:
import os
def file_data_and_path(filename):
if os.path.isfile(filename):
path = os.path.dirname(filename)
with open(filename,"rU") as f:
lines = f.readlines()
return lines,path
else:
print "Invalid File Path, File Doesn't exist"
return None,None
msg = 'Absolute Path to file: '
f_name = raw_input(msg).strip()
lines,path = file_data_and_path(f_name)
if lines != None and path != None:
for line in lines:
print lines
print 'Path:',path
mmm asume you want validations, this maybe can help you :)
def open_files(**kwargs):
arc = kwargs.get('file')
if os.path.isfile(arc):
arc_f = open(arc, 'r')
lines = arc_f.readlines()
for line in lines:
print line.strip()
if __name__ == "__main__":
p = raw_input("what is the path to the file (you can drag and drop):")
open_files(file=p)

Categories

Resources