I'm stuck on the best way to use a variable stored within a function to read a .csv file.
I've only used the with open before using a path like (r"C:/Users\James\Desktop\test_data.csv"). If I store (r"C:/Users\James\Desktop\test_data.csv") into FilePath = (r"C:/Users\James\Desktop\test_data.csv") and use with open(FilePath) as f: it works. So I'm sure I'm messing something up within my function def select_input_file(): I have tried with open(r,(input_file_path)) as f: with open(r(input_file_path)) as f: but cant get it to work. Fyi, using python 3.8.5. I've reduced the code to include what i think is necessary for this question. Cheers
import tkinter as tk
from tkinter import *
import tkinter.ttk as tkrttk
from PIL import Image, ImageFont, ImageTk
import csv
from tkinter import filedialog
root = tk.Tk()
def select_input_file():
global input_file_path
input_file_path = filedialog.askopenfile(filetypes=(("CSV files", "*.csv"),))
with open(input_file_path) as f:
reader = csv.DictReader(f, delimiter=',')
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Import", command=select_input_file)
root.mainloop()
rmodifier only applies to string literals, because string literals have to support special escape sequences. You don't need to worry about it if you are getting your file path from somewhere else.askopenfile()doesn't return a file path as you seem to expect, it returns an open file, which you can directly iterate over (and then explicitly.close(), since there's no way to usewithin this case). Or you can change that toaskopenfilename(), and leave the rest of your code as is.