关于python:如何修复:FileNotFoundError:[Errno 2]没有这样的文件或目录

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

我试图打开一个肯定保存到我的计算机上的文件时遇到问题("nyt-bestsellers.txt"),但每当我试图用代码打开它时,都会收到错误。

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

我考虑过使用完整路径打开文件的方法……但这是我将在本周晚些时候提交的作业的一部分。如果我用笔记本电脑上的特定路径打开文件,我担心它不会打开标记。请告知!

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


正如Ryan所说,每次打开一个相对名称的文件时,都需要明确当前的工作路径。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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()

如果您确认该文件将与您的python脚本文件一起使用,则可以在打开该文件之前进行一些准备工作:

1
2
3
4
5
6
7
8
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()