簡體   English   中英

如何創建一個對話框來選擇和打開將在程序中使用的文件

[英]How to create a dialog box to select and open file that will be used in the program

我有一個程序,該程序接受一個文件,復制該文件的第一列,然后將該列粘貼到第二個文件上。 該程序運行出色,但是我必須分配一個變量並將其等同於手動鍵入的文件路徑,以便找到文件。 我想知道是否通過使用類似Tkinter的對話框來創建一個對話框來選擇並打開我需要的任何文件,而不是將其存儲為新的文件路徑變量,我的程序仍然可以正常工作,並且比輸入文件路徑更好為變量。 但是,我嘗試創建對話框和兩個底部,但是我不知道如何從對話框中獲取選定的文件並將其轉換為File1或File 2變量,以便程序可以執行其操作。 到目前為止,這是我嘗試過的:

import os
import csv
import Tkinter
from Tkinter import *

boot = Tkinter.Tk()
topFrame = Frame(root)
topFrame.pack()


Button1 = Button(topFrame, text="Select File 1", fg="red")
Button2 = Button(topFrame, text="Select File 2", fg="blue")

Button1.pack(side=LEFT)
Button2.pack(side=LEFT)

boot.mainloop()

File1 = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/dyn_0.csv'#This is what I need to select from the dialog box
File2 = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/HiSAM1_data_160215_164858.csv'

root, ext = os.path.splitext(File2)
output = root + '-new.csv'

with open(File1) as r1, open(File2) as r2, open(output, 'a') as w:
writer = csv.writer(w)
merge_from = csv.reader(r1)
merge_to = csv.reader(r2)
# skip 3 lines of headers
for _ in range(3):
    next(merge_from)
for _ in range(1):
    next(merge_to)
for merge_from_row, merge_to_row in zip(merge_from, merge_to):
    # insert from col 0 as to col 0
    #merge_to_row.insert(0, merge_from_row[0])
    # replace from col 1 with to col 3
    merge_to_row[0] = merge_from_row[2]
    # delete merge_to rows 5,6,7 completely
    #del merge_to_row[5:8]
    writer.writerow(merge_to_row)

任何幫助將不勝感激,我真的很想學習如何做到這一點。 請記住,我是一個學習緩慢的人,我正在執行此程序,以解釋工作中的數據並研究我所在城市空氣中的臭氧濃度。 看來確實非常糟糕。請讓我知道我的問題是否必須進行任何格式化。 關於我的問題的任何意見將不勝感激。 多謝你們! :)

從您提供給我們的信息來看,我相信目前最好的方法是忘記GUI。 如果您只需要執行以下操作,就可以更快地處理數據:

option = input('would you like file 1 or 2? (1/2): ')
myfile = File1 if option == 1 else File2
with open(myfile) as fp:
  # do your work with the file

通過使用數據,而不是花費大量的令人沮喪的時間來使用GUI,您將從編碼時間中獲得更多價值。

編輯:

如果有很多文件可以使用,並且您希望用戶可以在不鍵入整個文件名的情況下從文件中進行選擇,那么我將在目錄中顯示文件列表,並要求用戶使用數。 (一些代碼摘自“ 如何列出目錄的所有文件?”

from os import listdir
from os.path import join

# get the list of files in mypath and store in a list
mypath = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/'
onlycsv = [f for f in listdir(mypath) if '.csv' in f]

# print out all the files with it's corresponding index
for i in range(len(onlycsv)):
  print( i, onlycsv[i] )

# prompt the user to select the file
option = input('please select a file by number: ')

# build out the full path of the file and open it
fullpath = join(mypath, onlycsv[option])
with open( fullpath ) as fp:
  # do work with file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM