[英]Python Pandas: Can I import a CSV through user input using a dynamic file path?
So I'm trying to create a very basic python UI where a user uploads a CSV with a list of cities and the program creates an inner join with a pre-existing database of zip codes returns a list of cities and their corresponding zip codes. So I'm trying to create a very basic python UI where a user uploads a CSV with a list of cities and the program creates an inner join with a pre-existing database of zip codes returns a list of cities and their corresponding zip codes. My code is functional so far.
到目前为止,我的代码可以正常工作。 I'd just like the user to be able to upload a CSV from anywhere in their system.
我只是希望用户能够从系统中的任何位置上传 CSV。 Right now, the program only reads from the python directory.
目前,该程序仅从 python 目录中读取。 I don't want to have to specify the file path of the input file.
我不想指定输入文件的文件路径。 Is there any way this can be done?
有什么办法可以做到这一点? Here's the code I have right now -
这是我现在拥有的代码 -
import tkinter as tk
from tkinter import filedialog
import pandas as pd
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()
def getCSV():
global cities
import_file_path = filedialog.askopenfilename()
cities = pd.read_csv('cities.csv')
zips = pd.read_csv('zips.csv')
output = pd.merge(cities, zips, on='state' and 'county', how='inner')
output.to_csv('output.csv', encoding='utf-8', index=False)
browseButton_CSV = tk.Button(text=" Upload City Data & Close ", command=getCSV, bg='green', fg='white',
font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=browseButton_CSV)
root.mainloop()
I'm kinda new to python and programming in general.我对 python 和一般编程有点陌生。 Just been learning it over the past month or 2. Any help is appreciated!
在过去的一两个月里刚刚学习它。感谢任何帮助!
Thanks, DJ谢谢,DJ
@gingerhaze's answer - @gingerhaze 的回答——
import tkinter as tk
from tkinter import filedialog
import pandas as pd
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()
def getCSV():
global cities
import_file_path = filedialog.askopenfilename()
cities = pd.read_csv(import_file_path)
zips = pd.read_csv('zips.csv')
output = pd.merge(cities, zips, on='state' and 'county', how='inner')
output.to_csv('output.csv', encoding='utf-8', index=False)
browseButton_CSV = tk.Button(text=" Upload City Data & Close ", command=getCSV, bg='green', fg='white',
font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 150, window=browseButton_CSV)
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.