我在尝试打开一个明确保存到我的计算机上的文件时遇到了问题(' NYT-bestsellers.txt'),但每当我尝试用我的代码打开它时,我得到了错误
FileNotFoundError:[Errno 2]没有这样的文件或目录:' NYT-bestsellers.txt'
我考虑使用您使用完整路径打开文件的方法......但这是我本周晚些时候提交的作业的一部分。如果我使用笔记本电脑中的特定路径打开文件,我担心它不会打开标记。请指教!
with open('NYT-bestsellers.txt', 'r') as file:
file = file.splitlines()
答案 0 :(得分:1)
正如Ryan所说,每次用相对名称打开文件时,都需要明确当前的工作路径。
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脚本文件一起使用,您可以在打开文件之前做一些准备工作:
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()