我有一个程序,它接受一个文件,复制该文件的第一列,然后将该列粘贴到第二个文件。该程序工作非常好,但我必须分配一个变量,并将其等同于手动输入的文件路径,以便找到该文件。我想知道是否通过使用像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)
任何帮助都会很感激,我真的很想学习如何做到这一点。请保持我的学习速度慢,我正在做这个程序来解释工作中的数据并研究我所在城市空气中的大气臭氧浓度。这看起来非常非常糟糕。如果在我的问题中必须进行任何格式化,请告诉我。任何有关我的问题的意见将不胜感激。多谢你们! :)
答案 0 :(得分:1)
根据您提供给我们的信息,我认为您现在最好的方法是忘记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。
编辑:
如果有很多文件可以使用,并且您希望用户能够从中进行选择而无需输入整个文件名,我会在目录中显示文件列表并要求用户从中进行选择他们有一个数字。 (一些代码取自How to list all files of a directory?)
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