简体   繁体   中英

How to fix: FileNotFoundError: [Errno 2] No such file or directory

I'm having an issue trying to open a file that is definitely saved to my computer ('NYT-bestsellers.txt'), but whenever I try opening it with my code I get the error

FileNotFoundError: [Errno 2] No such file or directory: 'NYT-bestsellers.txt'

I thought about using the method where you use the full path to open the file… but this is part of an assignment that I'll be submitting later this week. If I open the file using a specific path from my laptop, I'm worried that it won't open for the marker. Please advise!

with open('NYT-bestsellers.txt', 'r') as file:
    file = file.splitlines()

As Ryan said, every time you open a file by a relative name, you need to make clear for the current work path.

import sys
import os


current_work_directory = os.getcwd()    # Return a string representing the current working directory.
print('Current work directory: {}'.format(current_work_directory))
# Make sure it's an absolute path.
abs_work_directory = os.path.abspath(current_work_directory)
print('Current work directory (full path): {}'.format(abs_work_directory))
print()

filename = 'NYT-bestsellers.txt'
# Check whether file exists.
if not os.path.isfile(filename):
    # Stop with leaving a note to the user.
    print('It seems file "{}" not exists in directory: "{}"'.format(filename, current_work_directory))
    sys.exit(1)

# File exists, go on!
with open(filename, 'r') as file:
    file = file.splitlines()

If you confirm that the file will be along with your python script file, you can do some preparatory work before opening the file:

script_directory = os.path.split(os.path.abspath(__file__))[0]
print(script_directory)

abs_filename = os.path.join(script_directory, filename)
print(abs_filename)

with open(abs_filename, 'r') as file:
    file = file.splitlines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM