For AI Python for Beginners, C1M3_Assignment, the first exercise states “Define a Python function called read_article that takes a text_file (string) as a parameter and reads the contents of the file. The function should return the contents of the file.” However, when I run the code I receive the error “There was an error when running your function. Details: [Errno 2] No such file or directory: ‘text_file’“.
Can you help with this error? Seems like I”m trying to access a file that does not exist in the directory, however this file was specified in the instructions.
It looks like there is a spelling error: ‘text_file’“ is not the same as text_file.
text_file is a string variable that contains the file name. When making a call to the read_article() function, the variable text_file should be passed to the function.
Thank you for your feedback, however I’m not understanding your answer. If the instructions are
Define a Python function “read_article” and pass “text_file” as parameter
and my answer is
def read_article(file):
### START CODE HERE ###
# "Open" "text_file" in "read" mode
f = open("text_file", "r")
Your function definition for read_article() specified file as the input parameter, but your code gave the string “text_file” to the open() function, that is to say, you want to open a file named text_file. But text_file bears no relationship to the input parameter file, it is a different file and must be present in the file directory.
If your code is required to take the input parameter file containing the name of the file you want to open, then you need to change your code to use file and pass it to the open() function.