需要动态地从用户那里获取文件

时间:2019-07-11 10:33:26

标签: python tkinter

我正在编写一个我希望用户提供文件位置的代码,它将运行我已编码的检查。 在这里,我已经对excel路径进行了硬编码,但是我希望它是动态的。

我正在尝试Tkinter进行编码和动态读取,但是出现错误:

from tkinter import *
from tkinter.ttk import *
import pandas as pd
import csv
from tkinter.filedialog import askopenfile

root = Tk()
root.geometry('200x100')


def open_file():
    file = askopenfile(mode ='r', filetypes =[('Python Files', 
    '*.csv')])
      if file is not None:
         content = file.read()
            print(content)

btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)
prac = askopenfile(mode ='r', filetypes =[('Python Files', 
'*.csv')])
 content = prac.read()

content["latlong"] ='FALSE'
content.loc[(content["LONGITUDE"] >= 70.0000) & 
(content["LONGITUDE"] <= 
98.0000) & (content["LONGITUDE"] != 'nan') & 
 (content["LATITUDE"] != 
'nan'), ["latlong"]] = 'TRUE'
 file.to_csv("C:/Users/patesari/Desktop/python 
 work/practice1.csv")
 writer = content[content["latlong"]=='TRUE']
 writer.to_csv('C:/Users/patesari/Desktop/python 
 work/newfile1.csv', 
 index=False)
 writer = content[content["latlong"]=='TRUE']
 writer.to_csv('C:/Users/patesari/Desktop/python
 work/outputfiles/latlong1.csv', index=False)
 mainloop()

#但是此代码给了我一个错误:content [“ latlong”] ='FALSE'    #TypeError:“ str”对象不支持项目分配。  这段代码对我来说很好用,但是我已经弄乱了路径:

def latlong_func():
data = pd.read_csv(r'C:/Users/patesari/Desktop/python 
work/Gap1`.csv')
df = pd.DataFrame(data,columns=['SUPPLIER_ID','ACTION'])
data["latlong"] ='FALSE'
data.loc[(data["LONGITUDE"] >= 70.0000) & (data["LONGITUDE"] 
<= 98.0000)&
(data["LONGITUDE"] != 'nan') & (data["LATITUDE"] != 'nan'), 
["latlong"]] 
= 'TRUE'
data.to_csv("C:/Users/patesari/Desktop/python 
work/practice1.csv")
writer = data[data["latlong"]=='TRUE']
writer.to_csv('C:/Users/patesari/Desktop/python 
work/newfile1.csv', 
index=False)
writer = data[data["latlong"]=='TRUE']
writer.to_csv('C:/Users/patesari/Desktop/python 
work/outputfiles/latlong1.csv', index=False)

如果我使用tkinter,需要纠正什么。我是哪段代码    如果不使用tkinter,则应适用

1 个答案:

答案 0 :(得分:0)

您应该使用askopenfilename来获取文件名,而不要打开文件对象。您可以使用pd.read_csv(filename)而不是prac.read()

使用的文件名

所以首先我做了函数

def latlong_func(filename):
    data = pd.read_csv(filename)

    # rest

因此它获取文件名并与熊猫一起使用。

后来我做了函数

def get_filename():

    filename = askopenfilename(filetypes =[('Python Files', '*.csv')])

    if filename:
        lbl['text'] = filename
        latlong_func(filename)
    else:
        lbl['text'] = 'not selected'

获取文件名并执行latlong_func(filename)。它还在窗口的Label中显示文件名。

此功能已分配给按钮

btn = tk.Button(root, text='Open', command=get_filename)

完整代码:

import tkinter as tk
import pandas as pd
from tkinter.filedialog import askopenfilename


def latlong_func(filename):
    # filename instead of r'C:/Users/patesari/Desktop/python work/Gap1.csv'
    data = pd.read_csv(filename)

    #df = pd.DataFrame(data, columns=['SUPPLIER_ID','ACTION'])

    data["latlong"] = 'FALSE'
    data.loc[
        (data["LONGITUDE"] >= 70.0000) & (data["LONGITUDE"] <= 98.0000) &
        (data["LONGITUDE"] != 'nan') & (data["LATITUDE"] != 'nan'),
        ["latlong"]
    ] = 'TRUE'

    data.to_csv("C:/Users/patesari/Desktop/python work/practice1.csv")

    writer = data[data["latlong"]=='TRUE']
    writer.to_csv('C:/Users/patesari/Desktop/python work/newfile1.csv', index=False)
    writer.to_csv('C:/Users/patesari/Desktop/python work/outputfiles/latlong1.csv', index=False)


def get_filename():

    filename = askopenfilename(filetypes =[('Python Files', '*.csv')])

    if filename:
        lbl['text'] = filename # display filename in Label
        latlong_func(filename)
    else:
        lbl['text'] = 'not selected'


# --- main ---

root = tk.Tk()
root.geometry('200x100')

lbl = tk.Label(root, text='Select filename')
lbl.pack(side='top', pady=10)

btn = tk.Button(root, text='Open', command=get_filename)
btn.pack(side='top', pady=10)

root.mainloop()