I am trying to open a file in python. It is in a folder named R and the file I want to open is called PROTO.rtf
This is the code I have so far:
filepath = os.path.join(R, "PROTO.rtf")
file = open(filepath)
content = f.read()
This is the error it throws when I try to create my filepath:
NameError: name 'R' is not defined
3 Answers 3
R would need to be a string in this case. From your code snippet, it is not defined. You'd need to include quotes around it to make it a string literal, or define it above.
Comments
You currently have R being used as a variable. You didn't define a variable R. You want a string. If R is a folder in the current directory you want filepath = os.path.join("R", "PROTO.rtf"). If it is not in the current directory you will want filepath = os.path.join("/full/path/to/R", "PROTO.rtf")
This page includes a few good examples.
Comments
Define Variable R before using it. Once you defined your path you can always verify you file using os.path.isfile(file_name_with_path).
Ris a variable here, not a string. You have noRvariableRa variable? If not, then make it a string'R'