枚举glob.glob对象后变量namedf未定义问题求助
Fixing the "name 'namedf' is not defined" Error in Your Pandas Code
Hey there! Let's break down why you're hitting this error and get your code working properly.
What's Causing the Error?
The most likely culprit is that your glob.glob("F5331_FM003**") call isn't finding any matching files. If the loop never runs, namedf is never created, so when you try to print(namedf) outside the loop, Python throws the "not defined" error.
On top of that, there are a couple of other small issues (like using the deprecated append() method in pandas) we can fix to make your code more reliable.
Corrected Code
Here's a revised version of your script with explanations of the changes:
import os import glob import pandas as pd # Add the full path to your file pattern (assuming files live in V:/FM003) file_pattern = "V:/FM003/F5331_FM003**" matching_files = glob.glob(file_pattern) # First, check if any files were found if not matching_files: print("No files matched your pattern! Double-check your file path or wildcard syntax.") else: # Use a list to collect DataFrames (more efficient than repeated append) results_list = [] for counter, file in enumerate(matching_files): # Read the CSV with your specified parameters namedf = pd.read_csv( file, header=[0], skiprows=[0,1,2,3,4,5,6], index_col=[0], usecols=[0,1] ) results_list.append(namedf) print(f"Processed file {counter + 1}:") print(namedf) print("---") # Combine all DataFrames with pd.concat (replaces deprecated append()) results = pd.concat(results_list) print("\nFinal combined results:") print(results)
Key Changes Made:
- Added full file path: Without specifying
V:/FM003/,globsearches your current working directory (which might not be where your files are). - Added file existence check: This catches the case where no files match your pattern, preventing the "namedf not defined" error entirely.
- Replaced
append()withpd.concat(): Theappend()method is deprecated in pandas 2.0+, and using a list +concatis much more efficient for combining multiple DataFrames. - Moved
print(namedf)inside the loop: Now it prints each file's data as it's processed, which is more useful than printing a single (possibly undefined) variable at the end.
内容的提问来源于stack exchange,提问作者LMC94
相关产品推荐
相关产品推荐

