I'm writing this basic code that runs files on my computer but right now it can only open files from the directory it is in. is there a way to open files from anywhere on my computer or would I have to give the path for the file.
Here is my code:
def run(filename):
try:
import os
os.startfile(filename)
except:
WindowsError
print ("Thats not a valid file name")
while True:
filename = raw_input("Filename: ")
run(filename)
x = raw_input("Would you like to open another file? [y/n]: ")
if x == "n":
quit()
This opens and runs the files fine but only from the directory its saved in.
def run(filename):
for directoy,files,dirs in os.walk("C:\\"):
if filename in files:
return os.startfile(os.path.join(directory,filename))
fair warning it may be slow ...
you can do this a couple of different ways
either use entire paths
or change the directory its looking at
changing the directory is pretty easy
os.chdir("PATH TO DIRECTORY")
Related
I have this code:
import os
directory = "JeuDeDonnees"
for filename in os.listdir(directory):
print("File is: "+filename)
This code run and prints files name in a VSCode/Python environment.
However, when I run it in Sikuli-IDE I got this error:
[error] SyntaxError ( "no viable alternative at input 'for'", )
How can I make this for loop run or is there an alternative that can work?
Answer found ;
Basically, in my Sikuli-IDE environnement, there's layers of Python, Java, Jython... interlocking each other so the Path finding was tedious.
src_file_path = inspect.getfile(lambda: None) #The files we're in
folder = os.path.dirname(src_file_path) # The folder we're in
directory = folder + "\JeuDeDonnees" # Where we wanna go
for filename in os.listdir(directory) # Get the files
print(filename)
We're telling the Path where we are with the current file, get the folder we're in, then moving to "\JeuDeDonnees" and the files.
I am writing a code to zipFile multiple files based on user's input.
For example, user type couple file paths such as C:\Users\AAA\BBB, C:\Users\AAA\CCC,... The program will back up all these files into one single new zipFile.
Right now I'm using a loop (the code from "While True") and it works. But this only allows us to enter one path each time. Is there a neat way that we can input all the path at once and add each of them in a list (fileList here)?
And as I just started Python and I wrote it based on "A Byte of Python", I feel my code is kind of lengthy... Please feel free to provide recommendation to improve it. Thank you.
import os,time,zipfile
def createZip():
# Define the file path to save the file
savePath=input('Enter file save path-->')
if len(savePath)==0:
print('No path is found. Backup ends.')
# Define the file to be saved
else:
assert os.path.exists(savePath),"File path does not exist. Backup fails." # assert expression1, expression2, equals to if not expression1, raise AssertionError(expression2)
fileList=[]
while True:
filePath=input('Enter files to save. Enter "Done" to end.-->')
if filePath=='Done':
break
else:
if len(filePath)==0:
print('No path is found. Please enter files to save.')
else:
assert os.path.exists(filePath),"File path does not exist. Backup fails."
fileList.append(filePath)
today=savePath+os.sep+time.strftime('%Y%m%d')
now=time.strftime('%H%M%S')
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
comment=input('Enter a comment -->')
if len(comment)==0:
target=today+os.sep+now+'.zip'
else:
target=today+os.sep+now+'_'+comment+'.zip'
newZip=zipfile.ZipFile(target,'w',zipfile.ZIP_DEFLATED) # 'w' means write only; 'r' means read only
for fName in fileList:
for root,dirs,files in os.walk(fName):
for file in files:
newZip.write(os.path.join(root,file))
newZip.close()
print('backup to',target)
createZip()
Its mostly easy. You can split the text the user enters, but you need to worry about files with spaces in their names. The shlex lets you split a line the same way a unix-like shell would, which gives you the rules you need.
import shlex
fileList = []
while True:
filePaths = input('Enter files to save. Enter "Done" to end.-->')
if filePaths.lower() == "done":
break
for filePath in shlex.split(filePaths):
if not os.path.exists(filePath):
print("'{}' not found".format(filePath))
else:
fileList.append(filePath)
I'm relatively new to python and I'm working on a few projects. Say I'm running the script on partition D on Windows, so, for example, it's "D:/quarantine.py"
What I'm looking for right now is:
Taking a file from one folder (say, Desktop) and moving it to another folder (say, C:\Quarantine) - but I need to read both files and directories from the keyboard. The C:\Quarantine folder is created earlier with this code:
def create_quar(quar_folder):
try:
os.makedirs(quar_folder)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
dir_name = input("Enter the desired quarantine path: ")
if os.path.isdir(dir_name):
print ("Directory already existed.")
else:
print ("Directory created successfully!")
create_quar(dir_name)
Before moving the file, I need to store the file's previous location somehow. I was thinking of creating a .txt file in that C:\Quarantine folder.
If I ever change my mind, I call on a function that reads the .txt file I created earlier, and just moves the files back to the original folder. This, I have no idea how to implement.
I'm at a loss as to how to go about doing this. Was thinking of something like this for logging the path and moving the file:
path = input("Directory of file I need to move: ")
file = input("File name: ")
f = open(dir_name+"\log.txt",'w')
f.write(os.path.abspath(path+file))
shutil.move(path+file,dir_name+file)
dir_name is the variable I used earlier to read the Quarantine folder location, so I figured I could reuse it. As for the reading the log file and restoring, I have no idea.
Can anyone help?
You can use os.system() function by importing it from os. It will execute command in cmd/shell, but for the sub-process only.
I hope this is helpfull
Alright, so I managed to do this by myself in the end. In case anyone is interested you'll find samples of the code below. It's very rudimentary and can of course be optimized but it does work.
Main:
def Main():
dir_name = input("Enter the destination path: ")
if os.path.isdir(dir_name):
print ("Directory already existed.")
else:
print ("Directory created successfully!")
os.makedirs(dir_name)
choice = input("Would you like to (M)ove or (R)estore?: ")
if choice == 'M':
path = input("Directory of file you want moved: ")
file = input("Name of the file+extension: ")
file_path = path+'/'+file
move(file_path)
print ("Done.")
elif choice == 'R':
with open('quar_id.txt') as f:
quar_id = f.readline()
restore_from_quar(quar_id)
print ("Done.")
else:
print ("No valid option selected, closing...")
Move:
def move(filepath):
f = open('quar_id.txt','w')
f.write(path)
f.close()
os.chdir(dir_name)
shutil.move(file_path,dir_name+'/'+file)
Restore:
def restore(quar_id):
os.chdir(dir_name)
myfile = os.listdir(dir_name)
file = str(myfile)
file = file[2:-2]
shutil.move(file,quar_id+'/'+file)
couple of days back an infected computer infected my USB drive with a shortcut virus and. I had lots of software in that USB drive i plugged it in my Linux machine and cleaned a lot of files but what the virus did is it created an .exe file in each folder with that folder's name. Each .exe file is capable of infecting another PC. So me with a lot of time in my hand was trying to make a python script that goes to each folder check if a .exe file with that folder name exists delete it and run the function for every sub-folder recursively. but it is not working here what i made so far
#!/usr/bin/python
from __future__ import print_function
import os
import argparse
def deldir(fol):
# changing to the directory
os.chdir(fol)
#Trivial case delte the virus in the root folder
cwd = os.getcwd()
#getting just the name of the folder rather than full path by splitting from "/"
cwd = str(cwd).split('/')[-1]
#if any .exe file exists with that name
if any(str(cwd + '.exe') in s for s in os.listdir('.')):
# delete that file
os.remove(str(cwd + '.exe'))
print('Deleting virus file')
#making a list with all the contents in the directory
dirlist = os.listdir('.')
print(dirlist)
#Looping through the directory that we just made a list of its contents
for i in dirlist:
#checking if it is a directory or not
if os.path.isdir(i):
#changing dir to that directory
os.chdir(i)
#getting the current working directory
cwd = os.getcwd()
#getting just the name of the folder rather than full path by splitting from "/"
cwd = str(cwd).split('/')[-1]
#if any .exe file exists with that name
if any(str(cwd + '.exe') in s for s in os.listdir('.')):
# delete that file
os.remove(str(cwd + '.exe'))
print('Deleting virus file', str(cwd + '.exe'))
#listing filders in current directory
for j in os.listdir('.'):
#passing that subdirectory to the function itself if its a folder
if os.path.isdir(j):
deldir(j)
else:
print('Not a folder so skipping')
def main():
#parsing the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("fol", help="Directory to enter")
args = parser.parse_args()
#passing the command line argument with the folder path to "deldir" function
deldir(args.fol)
if __name__ == "__main__":
main()
Please point me to right direction i have no idea what i am doing wrong. Thanks for reading
Here what I see mistake in your code.
1
os.getcwd -> os.getcwd()
It's a function
2.
You using os.chdir(i) inside the for loop. this will work only first directory in that directory.
3.
The algorithm is wrong, It's not checking the directories level 1,3,5,... for virus.
As Hiro and MYGz's comments. os.walk/os.scandir is easier way to go for recursive directory. but your way is better for practice and learn programming.
I got it done the way i wanted with os.walk() it's really easy that way and that takes away the fun ! :'( . I was hoping to fix my own code but somethings not right. well anyways here's the working code if anyone encounters this type of virus or something.
#!/usr/bin/python
from __future__ import print_function
import os
import argparse
def deldir(fol):
for root, dirs, files in os.walk(fol):
try:
os.remove(str(root + '/' + str(root).split('/')[-1 ] + '.exe'))
except:
print('Does not exists' ,str(root + '/' + str(root).split('/')[-1 ] + '.exe'))
def main():
#parsing the command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("fol", help="Directory to enter")
args = parser.parse_args()
#passing the command line argument with the folder path to "deldir" function
deldir(args.fol)
if __name__ == "__main__":
main()
from random import *
import os
def createFile(randomNumber):
with open("FileName{}.txt".format(randomNumber), "w") as f:
f.write("Hello mutha funsta")
def deleteFile():
directory = os.getcwd()
os.chdir(directory)
fileList = [f for f in directory if f.endswith(".txt")]
for f in fileList:
os.remove(f)
print ("All gone!")
fileName = input("What is the name of the file you want to create? ")
contents = input("What are the contents of the file? ")
start = input("Press enter to start the hax. Enter 1 to delete the products. ")
randomNumber = randint(0, 1)
while True:
if start == (""):
for i in range(0):
createFile(randomNumber)
randomNumber = randint(0,9999)
break
elif start == ("1"):
deleteFile()
break
else:
print ("That input was not valid")
Above is code I've made to create as many text files as I specify (currently set to 0). I am currently adding a feature to remove all the text files created, as my folder now has over 200,000 text files. However, it doesn't work, it runs through without any errors but doesn't actually delete any of the files.
that is very wrong:
def deleteFile():
directory = os.getcwd()
os.chdir(directory)
fileList = [f for f in directory if f.endswith(".txt")]
for f in fileList:
os.remove(f)
you change the directory: not recommended unless you want to run a system call, mostly you change it to the current directory: it has no effect.
your list comprehension doesn't scan the directory but a string => f is a character! Since it doesn't end with .txt, your listcomp is empty
To achieve what you want you may just use glob (no need to change the directory and pattern matching is handled automatically):
import glob,os
def deleteFile():
for f in glob.glob("*.txt"):
os.remove(f)
this method is portable (Windows, Linux) and does not issue system calls.
For deleting all the files in the directory with name as FileName{some_thing}.txt, you may use os.system() as:
>>> import os
>>> os.system("rm -rf /path/to/directory/FileName*.txt")