I'm working on an online tutorial for Python, & I'm trying to go a little farther for an example problem than it calls for.
The objective is to rename all the files in a folder. My addition is to prompt the user for the folder, rather than hardcoding it.
I've tried the suggestions in Python: user input and commandline arguments, but when I run the script no prompt text is displayed.
As it stands my script looks like this:
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in ListDir(f):
print("Current file is '" + f)
I imagine I'm misunderstanding the answers in the question I linked to, and was hoping someone could clarify the responses for me. Especially since that thread mixes 2.7 and 3.x.
Thanks!
f is undefined when you loop through it. Did you mean ListDir(Fol)? And also ListDir is undefined too.
But above all you are not calling the RName_Files function in your program, try addding RName_Files() at the end of the script.
What could work
import os
ListDir = os.listdir
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")
#Iterate through the files in the folder
for f in ListDir(Fol):
print("Current file is '" + f)
if __name__ == "__main__":
RName_Files()
You should also follow the PEP8 naming conventions for variables and function names. In python variables and functions are snake_case, while class names are CamelCase. And you can also be more clear with your names, rename_files instead of RName_Files, folder or path instead of Fol, file_name instead of f.
Which will look like this:
from os import listdir
def rename_files():
#Get the folder to user
path = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")
#Iterate through the files in the folder
for file_name in listdir(path):
print("Current file is " + file_name )
# do something with file_name
if __name__ == "__main__":
rename_files()
You need to call your method
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in os.listdir(fol):
print("Current file is '" + f)
RName_Files()
The "pythonic" way to do this would be like this:
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in ListDir(Fol):
print("Current file is '" + f)
def main():
RName_Files()
if __name__ == "__main__":
main()
Basically you defined your function using def but never actually called it. Its good practice to have a main function to call the ones you've created and to call them in this fashion.
Related
I don't think that the following code is efficient enough to search for a filename in the current directory. The filename will be stored as a string, so will python be able to search a 'filename' string from the directories that are non-string?
filename = input("What would you like to name the File? ")
import os
if f"{filename}.txt" in os.getcwd():
print(True)
os.getcwd() returns the name of the directory itself, not a list of files (see https://www.tutorialspoint.com/python/os_getcwd.htm)
You want to try something like:
import os
for file in os.listdir("/mydir"):
if file == f"{filename}.txt:
print("File Found")
Also, you need to try-except statement for this code snippet. Otherwise, at the wrong file, the app will be crashed.
import os
# Getting current folder path
cmd = os.getcwd()
# getting file name from user
file_name = input('Enter file name to be search : ')
#Looping through all folder and files in the current directory
for file in os.listdir(cmd):
# compare the file name user entered with file names from current
# directory file name
if file == f"{file_name}.txt":
print("File Found")
I have two scripts. The first script outputs to a file a list of folders and files, then it calls a second python script to read that file and print it to screen. The second script is called but nothing ever prints to the screen and I'm not sure why. No error message is thrown.
First Script:
#!/bin/python
from subprocess import call
import os.path
import os
def main():
userRequest=raw_input("""Type the path and folder name that you'd like to list all files for.
The format should begin with a slash '/' and not have an ending slash '/'
Example (/var/log) *Remember capital vs. lower case does matter* :""")
userInputCheck(userRequest)
def userInputCheck(userRequest):
lastCharacter=userRequest[-1:]
if lastCharacter=="/":
userRequest=userRequest[:-1]
folderCheck=os.path.isdir(userRequest)
if folderCheck != True:
print("\nSorry, '"+userRequest+"' does not exist, please try again.\n")
requestUserInput()
else:
extractFileList(userRequest)
def extractFileList(userRequest):
fileList=open('/tmp/fileList.txt', 'a')
for folderName, subFolderName, listFiles in os.walk(userRequest):
fileList.write(folderName+":\n")
for fileName in listFiles:
fileList.write(fileName+"\n")
fileList.write("\n")
fileList.close
os.system("readFile.py /tmp/fileList.txt")
if os.path.isfile("/tmp/fileList.txt"):
os.remove("/tmp/fileList.txt")
if __name__ == "__main__":
main()
Second Script:
#!/bin/python
import sys
userFile=sys.argv[1]
f = open(userFile, 'r')
fileInfo=f.read()
sys.stdout.write(fileInfo)
sys.stdout.flush()
f.close
Hey and thanks for all of your answers. I try to write a piece of python code that only executes once, (first time the program is installed) and copies the program into the windows startup folders.
(C:\Users\ USER \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup)
That's the code i wrote for this. (Please don't judge me. I know it's
very shitty code. But I'm very new to coding. (this is the second
little program i try to write)
import os
import shutil
#get username
user = str(os.getlogin())
user.strip()
file_in = ('C:/Users/')
file_in_2 = ('/Desktop/Py Sandbox/test/program.py')
file_in_com = (file_in + user + file_in_2)
folder_seg_1 = ('C:/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
#create FolderPath
folder_com = (folder_seg_1 + user + folder_seg_2)
shutil.copy2(file_in_com, folder_com)
Because i got an error, that there is no such internal, external,
command, program or batch file named Installer. I tried to generate a batch file with
nothing in it that executes when the installation process is finished.(But the error is still there.)
save_path = 'C:/Windows/assembly/temp'
name_of_file = str("Installer")
completeName = os.path.join(save_path, name_of_file+".bat")
file1 = open(completeName, "w")
file1.close()
The main idea behind this that there is my main Program, you execute
it it runs the code above and copies itself to the startup folder.
Then the code the whole installer file gets deleted form my main
program.
import Installer
#run Installer File
os.system('Installer')
os.remove('Installer.py')
But maybe there's someone out there who knows the answer to this problem.
And as I said earlier, thanks for all of your answers <3.
BTW I'm currently using Python 3.5.
Okay guys now I finally managed to solve this problem. It's actually not that hard but you need to think from another perspective.
This is now the code i came up with.
import os
import sys
import shutil
# get system boot drive
boot_drive = (os.getenv("SystemDrive"))
# get current Username
user = str(os.getlogin())
user.strip()
# get script path
script_path = (sys.argv[0])
# create FolderPath (Startup Folder)
folder_seg_1 = (boot_drive + '/Users/')
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup')
folder_startup = (folder_seg_1 + user + folder_seg_2)
#check if file exits, if yes copy to Startup Folder
file_name = (ntpath.basename(script_path))
startup_file = (folder_startup + ("/") + file_name)
renamed_file = (folder_startup + ("/") + ("SAMPLE.py"))
# checkfile in Startup Folder
check_path = (os.path.isfile(renamed_file))
if check_path == True:
pass
else:
shutil.copy2(script_path, folder_startup)
os.rename(startup_file, renamed_file)
This script gets your username, your boot drive, the file location of
your file than creates all the paths needed. Like your personal
startup folder. It than checks if there is already a file in the
startup folder if yes it just does nothing and goes on, if not it
copies the file to the startup folder an than renames it (you can use that if you want but you don't need to).
It is not necessary to do an os.getenv("SystemDrive") or os.getlogin(), because os.getenv("AppData") already gets both. So the most direct way of doing it that I know of is this:
path = os.path.join(os.getenv("appdata"),"Microsoft","Windows","Start Menu","Programs","Startup")
I'm running a python file named test.py . I have a folder in the same directory named Model. Inside Model I have several other folders (like UserMgmt, GPO, DNS etc) each containing different python programs. Now, I want to run python program from the UserMgmt or DNS or GPO folder based on the users choice. I've tried..
foldername = raw_input('Enter foldername:');
filename = raw_input('Enter filename:');
from Model.foldername import filename;
But it is showing error 'Invalid Syntax'. I have to import the python files as I'll be using variables and functions from those files. But the python file and the path to the file is dependent on the user. How to import the python file in this scenario ?
Please Help...
Thank you in advance.
you can use importlib or imp module
importlib will be good to import some module relative to current dir
import importlib
# foldername need to be in same dir with this script
foldername = raw_input('Enter foldername:')
# enter filename without .py for this case
filename = raw_input('Enter filename:')
test = importlib.import_module(foldername + '.' + filename)
# for example, foldername = 'GPO', filename = 'test'
# this will import GPO\test.py
if you wanna import some file from arbitrary path, you can use imp module
import imp
import os
# foldername can be from anywhere
foldername = raw_input('Enter foldername:')
# enter filename with .py for this case
filename = raw_input('Enter filename:')
test = imp.load_source(filename ,os.path.join(foldername, filename))
# for example, foldername = r'C:\NGO', filename = 'test.py'
You can't use the variables with this syntax.
In your code you are literally importing a filename from foldername module.
Try using following code:
exec("from Model.{} import {}".format(foldername, filename))
When it comes to dynamic imports, importlib.import_module() is your friend. But if you only want to execute a given python script based on it's path you can simply use os.system() or execfile().
Try to use __import__() and if you use python2.7+ or 3.1+ it's better to use exec .
I have this code that searches all the files from the given directory, but I want to change it so that it can search a file from the users input? and then ask again if the file is not found? The following code i have is:
import os
import sys
from stat import *
def depthsearch(directory):
for files in os.listdir(directory):
fileItem = os.path.join(directory, files)
fileItemStatInfo = os.stat(fileItem)
if S_ISDIR(fileItemStatInfo.st_mode):
depthsearch(fileItem)
elif S_ISREG(fileItemStatInfo.st_mode):
print("Found File:", fileItem)
depthsearch("C:")
What about
depthsearch(raw_input()) # or 'input()' for Python 3
To check if a given string represents a valid directory, you can use os.path.isdir(). So you could wrap your call to depthsearch() in a while loop that keeps asking the user for input until they provide a valid directory.
You can get input by using:
Python 2.X's raw_input function:
s = raw_input()
Python 3.X's input function:
s = input()
def depthsearch(directory, fileName):
for files in os.listdir(directory):
fileItem = os.path.join(directory, files)
fileItemStatInfo = os.stat(fileItem)
if S_ISDIR(fileItemStatInfo.st_mode):
depthsearch(fileItem,filename)
elif S_ISREG(fileItemStatInfo.st_mode or (files==filename):
print("Found File:", fileItem)
depthsearch("C:", "python.exe")
This allow you to search a file in a directory. It just test if the name are the same.