I have recently started learning python.
I use code runner to run my python code in vc.
I have been trying to use the open('___.txt') function in python but it gives me an error every time.
I ran the code in command prompt and it worked flawlessly.
I assume it's a problem in code runner, although i could be wrong.
Here is my code
#!/usr/bin/python3
def main():
f = open('nums.txt')
for line in f.readlines():
print(line)
if __name__ == "__main__": main()
Here is the error
_Traceback (most recent call last):
File "e:\Python\Projects\Lynda\9.1\open.py", line 8, in
if __name__ == "__main__": main()
File "e:\Python\Projects\Lynda\9.1\open.py", line 4, in main
f = open('nums.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'nums.txt'_
PS - I can assure you that the txt file exists in the same folder. You can check yourself in the screenshots.
ThankYou for your help. :)
I appreciate it.
The problem is that in open('nums.txt'), you are using relative path instead of absolute path. You should not assume the CWD (current working directory). In Code Runner, the CWD is the root folder of workspace, i.e. "e:\Python\Projects\Lynda\". Therefore, two options to fix:
e:\Python\Projects\Lynda\9.1\nums.txt) or correct relative path (9.1\nums.txt) in open('nums.txt'){
"code-runner.fileDirectoryAsCwd": true
}
@formulahendry That makes complete sense. Thank you for the help, that fixed my problem.
Most helpful comment
The problem is that in
open('nums.txt'), you are using relative path instead of absolute path. You should not assume the CWD (current working directory). In Code Runner, the CWD is the root folder of workspace, i.e."e:\Python\Projects\Lynda\". Therefore, two options to fix:e:\Python\Projects\Lynda\9.1\nums.txt) or correct relative path (9.1\nums.txt) inopen('nums.txt')