首页 > 解决方案 > How to use a user input variable to load a csv file in Python

问题描述

Im trying my hand at writing my first Python tool for a part of my job to automate a process (a raffle/random drawing). I want it to ask the user 2 questions: "What month are you drawing for?" and "What year are you drawing for?"

I then want it to take the user input and load/open a csv file in the directory in python using their input.. all the csv files are titled like so..

March2019.csv
April2019.csv

So in my mind I believe that if I store those user inputs as variable I can use them to call the proper csv file

I have already tried the code shown below, but the problem is, you cant put the variables inside the '' when using the pandas.read('') function because it reads them as a string instead of as what the variables represent

month = input("What month are you drawing for? ")

year = input("What year are you drawing for? ")

import pandas
df = pandas.read_csv('month year'.csv)

this doesnt work because its literally looking for a file called 'month year'.csv

标签: python-3.xpandascsv

解决方案


尝试:

df = pandas.read_csv(month+str(year)+'.csv')

推荐阅读