QFileDialog: adding extension automatically when saving file? - c++

When using a QFileDialog to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdfFile(fileDialog.selectedFiles().first());
now when the user enters "foo" as the name, the file will be saved as "foo", not as "foo.pdf". So the QFileDialog doesn't add the extension automatically. My question: How can I change this?

You could use QFileDialog::setDefaultSuffix():
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (e.g. "txt" indicates a text file).

For multiple file filters, the following can be done.
import re
import os
def saveFile(self):
path, fileFilter = QFileDialog().getSaveFileName(self, "Save file",
"", "Gnuplot Files (*.plt)"
+ ";;" + "Gnuplot Files (*.gp)"
+ ";;" + "Gnuplot Files (*.gpt)"
+ ";;" + "Text Files (*.txt)")
selectedExt = re.search('\((.+?)\)',fileFilter).group(1).replace('*','')
# Attach extension as per selected filter,
# if file does not have extension.
if not os.path.splitext(path)[1]:
path = path + selectedExt
print(path)

Related

select some of (EOF) extension files in specific folder based on part of filenames in text file :explained in image file with connected arrow

I want to Select files in specific folder based on part of the name of files(date)
so:
1-first: (in names.csv) extract part of file name(date) :find all("1SDV_(\d+)T", name)
2-second: (in name of files in specific folder) extract part of file name(date):
find all ("OPOD__(\d+)T", name)
of all (EOF) extension file names in specific folder
3-third: relate extraction: as image that I attached (red connected arrow)
my code is not complete please help me to complete it
enter code here
import OS
import re
# open the file, make a list of all filenames, close the file
with open('names.csv') as name file:
# use .strip() to remove trailing whitespace and line breaks
names= [line strip() for line in name file]
for name in names:
res = re find all ("1SDV_(\d+)T", name)
if not res: continue
print res[0]
# You can append the result to a list
# Find all ("OPOD__(\d+)T")
# how can I relate (EOF) extension files name to res like image file I
attached
# move the selected (EOF) extension file
OS rename(OS path join('path', (EOF) file extension folder),
'/path/to/somewhere/else')
break
csv or text file is like this:
S1A_IW_SLC__1SDV_20190826T022837_20190826T022904_028734_0340DD_654D-SLC
S1A_IW_SLC__1SDV_20190919T022838_20190919T022905_029084_034D09_0129-SLC
S1A_IW_SLC__1SDV_20191013T022839_20191013T022906_029434_03590E_A824-SLC
S1A_IW_SLC__1SDV_20191106T022839_20191106T022906_029784_036538_06CC-SLC
S1A_IW_SLC__1SDV_20191130T022838_20191130T022905_030134_037166_4019-SLC
S1A_IW_SLC__1SDV_20191224T022837_20191224T022904_030484_037D7B_0FC4-SLC
S1A_IW_SLC__1SDV_20210217T062720_20210217T062747_036626_044D90_4570-SLC
.
.
.
And (EOF) extension files in specific folder are like :
S1A_OPER_AUX_POEORB_OPOD_20190915T120743_V20190825T225942_20190827T005942.EOF
S1A_OPER_AUX_POEORB_OPOD_20190916T120658_V20190826T225942_20190828T005942.EOF
S1A_OPER_AUX_POEORB_OPOD_20190917T120653_V20190827T225942_20190829T005942.EOF

Traversing multiple folders for searching the same file in multiple foders in python

search the same file in multiple folders
I have tried with os.walk(path) but I am not getting the nested folders traversing
for current_root, folders, file_names in os.walk(self.path, topdown=True):
for i in folders:
print i
for filename in file_names:
count+= 1
file_path = os.path.join(current_root + '\\' + filename)
#print file_path
self.location_dictionary[file_path] = filename
in my code, it will print all folders but it will not enter to the nested folders recursively
ex: I have subdir,subdir1,subdir2 and in subdir I have another dir called abc
in subdir and abc both contain same file name I want to read that file
os.walk does not work that way.
for each current_root it traverses, it provides the list of directories and files directly under it.
You're nesting the loops, which does ... well I don't know...
Here you don't need the folder (so just mute the argument). current_root already contains that info for your files:
for current_root, _, file_names in os.walk(self.path, topdown=True):
for filename in file_names:
count+= 1
file_path = os.path.join(current_root,filename)
#print file_path
self.location_dictionary[file_path] = filename
aside: creating a dictionary with full file as key and filename as value looks, well, not what you want (the same information could be stored in a set or list and os.path.basename could be used to compute the filename. Maybe it's reverse (filename => full path), provided that there are no duplicate filenames.

QFileDialog::setNameFilter only show files with no extension

In my project I open a QFileDialog to have the user select a file to open. The file I'm expecting does not have an extension. I would like to set a filter that only shows files that don't have any extension.
Currently, I filter out any files that don't have the exact name:
QString path;
QString desktopPath = QStandardPaths::standardLocations(QStandardPaths::DesktopLocation).at(0);
path = QFileDialog::getOpenFileName(this, tr("Select File"), desktopPath + "\\DATAFILE", tr("DATAFILE file (DATAFILE)"));
However, in the case where the file might be renamed (for example, DATAFILE (2)) that file wouldn't show up because the name doesn't match exactly.
Filtering it to accept all files is not what I want either because that would allow any file type to be selected.
Any suggestions? Thanks for your time.

Giving multiple file names as link to Tkinter GUI in python and opening with default application

#python version 2.7.11
import os
from Tkinter import *
fileName = "Nothing" #fileName is required so that the callback function can link the current file name with button click
def callback(event):
#os.startfile() works only on windows machine
os.startfile(fileName) #opens the fileName with its default application (in my case a pdf viewer)
def makeLink(file):
global fileName
fileName = file
link = Label(textbox, text=fileName, fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", callback)
oldDir = os.getcwd()
newDir = os.chdir("pdf folder") #pdf folder contains some pdf files
root = Tk()
textbox = Text(root)
textbox.pack()
allFiles = os.listdir(os.getcwd()) #makes a list of files present in current directory
for file in allFiles:
makeLink(file)
root.mainloop()
os.chdir(oldDir)
I want to select the files of a folder (in above code it's pdf folder) containing some pdf files and display them as a link in GUI window. When pressed on the link, the file should open with it's default application (so the pdf file should open with default pdf viewer). My code is displaying the file names of every file in the "pdf folder" as link. But on clicking on every link, the last file of the folder is opening. Can someone correct the code so that every link opens it's own file. I searched everywhere but found nothing on this topic.
This is exactly what you have coded so far. You're making fileName global and then setting fileName = file where the last assignment will be the last item in your loop. So, this is why it is opening the last file. If you want a user to be able to select options from these I'd suggest a combobox or some other widget that takes the list of filenames as the options. You can then bind on <<ComboboxSelected>> to call your makeLink function.
you should really also rename file. file is a built in.
This problem can surely be done by combobox but when i have many pdf files then every file is placed in a combobox which is not a good way to interact.
Here I have taken two count variables ---- one is global count and one localCount. The localCount is required to remember the count of which file is to be opened.
from Tkinter import *
import os
def callback(count):
os.system("open "+fileNames[count])
def makeLink(files):
localCount = count
link = Button(frame1, text=(count , files), bg="light blue", cursor="hand2", command=lambda: callback(localCount))
link.pack()
oldDir = os.getcwd()
newDir = os.chdir("pdf folder")
fileNames = os.listdir(os.getcwd())
root = Tk()
frame1 = Frame(root)
frame1.pack()
count = 0
for files in fileNames:
makeLink(files)
count += 1
root.mainloop()
os.chdir(oldDir)

Python finds a string in multiple files recursively and returns the file path

I'm learning Python and would like to search for a keyword in multiple files recursively.
I have an example function which should find the *.doc extension in a directory.
Then, the function should open each file with that file extension and read it.
If a keyword is found while reading the file, the function should identify the file path and print it.
Else, if the keyword is not found, python should continue.
To do that, I have defined a function which takes two arguments:
def find_word(extension, word):
# define the path for os.walk
for dname, dirs, files in os.walk('/rootFolder'):
#search for file name in files:
for fname in files:
#define the path of each file
fpath = os.path.join(dname, fname)
#open each file and read it
with open(fpath) as f:
data=f.read()
# if data contains the word
if word in data:
#print the file path of that file
print (fpath)
else:
continue
Could you give me a hand to fix this code?
Thanks,
def find_word(extension, word):
for root, dirs, files in os.walk('/DOC'):
# filter files for given extension:
files = [fi for fi in files if fi.endswith(".{ext}".format(ext=extension))]
for filename in files:
path = os.path.join(root, filename)
# open each file and read it
with open(path) as f:
# split() will create list of words and set will
# create list of unique words
words = set(f.read().split())
if word in words:
print(path)
.doc files are rich text files, i.e. they wont open with a simple text editor or python open method. In this case, you can use other python modules such as python-docx.
Update
For doc files (previous to Word 2007) you can also use other tools such as catdoc or antiword. Try the following.
import subprocess
def doc_to_text(filename):
return subprocess.Popen(
'catdoc -w "%s"' % filename,
shell=True,
stdout=subprocess.PIPE
).stdout.read()
print doc_to_text('fixtures/doc.doc')
If you are trying to read .doc file in your code the this won't work. you will have to change the part where you are reading the file.
Here are some links for reading a .doc file in python.
extracting text from MS word files in python
Reading/Writing MS Word files in Python
Reading/Writing MS Word files in Python