Python自定义文件导入函数报错NameError: name 'filename'未定义求助
Hey there, let's walk through what's causing this error and how to fix it properly—your original function had a common beginner misunderstanding about how Python function parameters work.
The Immediate Error
First, the direct reason you're seeing:
NameError - name 'filename' not defined
When you ran importdata('File.csv',filename,datasetname), you tried to pass filename and datasetname as arguments, but you never created those variables anywhere before the call! Python has no idea what filename refers to, hence the error. But this is just a symptom of a bigger issue with how your function was designed.
Why Your Original Function Wasn't Working
Let's look at your initial function code:
def importdata(path,temp_file_name,dataset_name): temp_file_name = os.path.join('..', 'data', path) dataset_name = pd.read_csv(temp_file_name, index_col='time') var1, var2, var3, var4 = dataset_name.keys()
See the problem? You declared temp_file_name and dataset_name as parameters, but then immediately reassign them inside the function—you never use the values you passed into them! Those two parameters are completely unnecessary here.
In Python, function parameters are for receiving values you pass in, not for telling the function which variables to populate outside of it. Your original non-function code worked because you explicitly defined variables like filename and assigned values to them directly.
A Clean, Fixed Version of the Function
Instead of trying to pass variable names (which isn't how Python operates), rewrite the function to return the data and column names so you can assign them to variables outside. Here's a better approach that matches your working non-function logic:
import os import pandas as pd def importdata(path): # Build the full file path relative to your script file_path = os.path.join('..', 'data', path) # Load the CSV into a DataFrame dataset = pd.read_csv(file_path, index_col='time') # Extract the column names var1, var2, var3, var4 = dataset.keys() # Return everything you need to use outside the function return dataset, var1, var2, var3, var4
Call it like this—no undefined variables, and you get all the values you need:
datasetname, var1, var2, var3, var4 = importdata('File.csv')
Quick Notes on Your Final Working Code
Your modified code works, but a couple of best practice tips:
- Using
globalto exposevar1-var4isn't ideal—it creates hidden side effects and makes your code harder to debug. Returning values (like the example above) is a cleaner, more modular approach. - Make sure you initialize the
datavariable as an empty list (data = []) before calling the function, otherwise you'll hit anotherNameError. - The
*pathsargument is a great touch for handling multiple files at once—nice improvement!
内容的提问来源于stack exchange,提问作者Danny

