Untitled
Anonymous
plain_text
09/12/2024 3:30 AM
4.8 KB
34
Indexable
import sys
import csv
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QFileDialog, QTextEdit
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QDesktopServices
import os
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# Thiết lập cửa sổ chính
self.setWindowTitle('CSV File Processor')
self.setGeometry(100, 100, 500, 400)
# Layout để sắp xếp các thành phần giao diện
layout = QVBoxLayout()
# Nhãn hiển thị
self.label = QLabel('Chọn tệp để xử lý', self)
layout.addWidget(self.label)
# Nút chọn file
self.btn_select_file = QPushButton('Chọn file', self)
self.btn_select_file.clicked.connect(self.open_file_dialog)
layout.addWidget(self.btn_select_file)
# Nút để mở file CSV
self.btn_open_csv = QPushButton('Mở file CSV', self)
self.btn_open_csv.clicked.connect(self.open_csv_file)
self.btn_open_csv.setDisabled(True) # Vô hiệu hóa nút cho đến khi có file CSV
layout.addWidget(self.btn_open_csv)
# Nút mở thư mục chứa file CSV
self.btn_open_folder = QPushButton('Mở thư mục chứa CSV', self)
self.btn_open_folder.clicked.connect(self.open_csv_folder)
self.btn_open_folder.setDisabled(True)
layout.addWidget(self.btn_open_folder)
# TextEdit để hiển thị nội dung CSV
self.text_edit = QTextEdit(self)
self.text_edit.setReadOnly(True)
layout.addWidget(self.text_edit)
self.setLayout(layout)
def open_file_dialog(self):
# Mở hộp thoại để chọn file
options = QFileDialog.Options()
file_path, _ = QFileDialog.getOpenFileName(self, "Chọn tệp để xử lý", "", "All Files (*);;Text Files (*.txt)", options=options)
if file_path:
self.label.setText(f'Đã chọn: {file_path}')
# Xử lý file (ví dụ đọc file, và lưu ra CSV)
self.process_file(file_path)
def process_file(self, file_path):
# Ví dụ: Đọc nội dung file và lưu vào CSV
csv_file = 'output.csv'
with open(file_path, 'r') as infile, open(csv_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
for line in infile:
# Giả định mỗi dòng trong file input là một hàng trong CSV
writer.writerow([line.strip()])
# Cập nhật nút mở file CSV và mở thư mục
self.btn_open_csv.setDisabled(False)
self.btn_open_folder.setDisabled(False)
self.label.setText(f'Đã xử lý và xuất ra: {csv_file}')
self.csv_file_path = csv_file # Lưu lại đường dẫn file CSV
def open_csv_file(self):
# Hiển thị nội dung file CSV trong QTextEdit
if os.path.exists(self.csv_file_path):
with open(self.csv_file_path, 'r') as file:
content = file.read()
self.text_edit.setPlainText(content)
def open_csv_folder(self):
# Mở thư mục chứa file CSV
if os.path.exists(self.csv_file_path):
folder_path = os.path.dirname(os.path.abspath(self.csv_file_path))
QDesktopServices.openUrl(QUrl.fromLocalFile(folder_path))
# Khởi tạo và chạy ứng dụng
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())
Editor is loading...
Leave a Comment