如果你想要获取文件夹路径而不是单个文件路径,可以使用QFileDialog.getExistingDirectory()
方法。以下是修改后的示例代码:
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog
import shutil
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("File Saving Example")
# 创建按钮并连接槽函数
self.button = QPushButton("Select Files and Folders", self)
self.button.clicked.connect(self.save_files_and_folders)
def save_files_and_folders(self):
# 打开文件对话框选择要保存的文件和文件夹
file_dialog = QFileDialog()
# 获取单个或多个文件路径以及一个文件夹路径
files_paths, folder_path = file_dialog.getOpenFileNames(self,
"选择多个文件",
default_dir,
"Images (*.png *.jpg);;Text files (*.txt)")
if folder_path:
# 指定保存图片、文本和文件夹的目标路径
image_folder = "path/to/image/folder"
text_folder = "path/to/text/folder"
folder_destination = "path/to/destination/folder"
for file_path in files_paths:
if file_path.endswith(".txt"):
dest_path = f"{text_folder}/{os.path.basename(file_path)}"
shutil.copy(file_path, dest_path) # 复制文本文件
folder_name = os.path.basename(folder_path)
dest_path = f"{folder_destination}/{folder_name}"
shutil.copytree(folder_path, dest_path) # 复制整个文件夹
if __name__ == "__main__":
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
在这个修改后的示例代码中,我们添加了folder_path
变量来获取选择的文件夹路径。如果用户没有选择文件夹,则folder_path
将为空。
现在你可以同时选择多个文件和一个文件夹,然后将它们保存到不同的目标位置。请确保指定的目标文件夹已经存在,并且避免将源文件或源文件夹复制到相同的目标位置,以防止出现意外结果。
希望这对你有所帮助!如有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问