如何将文件名前缀作为函数参数构建.dta文件路径?
Oh I see the issue here! In your current code, you're using the string literal "code_dataset.dta"—so Python is literally looking for a file named exactly code_dataset.dta, not replacing the code variable with your input prefix. That's why you're getting the "file doesn't exist" error.
To fix this, you need to dynamically insert the code parameter into the file path string. Here are the three most common and clean ways to do this in Python:
1. Using F-Strings (Recommended for Python 3.6+)
F-strings are the most readable and concise option. Just add an f before the string and wrap your variable in curly braces {}:
def import_stata(code): df = pd.read_stata(f"{code}_dataset.dta") return df
2. Using str.format()
If you're working with an older Python version (pre-3.6), the format() method is a reliable alternative:
def import_stata(code): df = pd.read_stata("{}_dataset.dta".format(code)) return df
3. String Concatenation
You can also directly concatenate the string parts, though this is less readable if you have more complex paths later:
def import_stata(code): df = pd.read_stata(code + "_dataset.dta") return df
All three methods will replace the code variable with your input value (e.g., if you call import_stata("abc"), it will look for abc_dataset.dta instead of the literal code_dataset.dta).
Just make sure the actual file exists in your working directory (or you include the full file path along with the dynamic prefix if it's stored in another folder!).
内容的提问来源于stack exchange,提问作者yogz123

