打开文件夹时,VS Code如何处理文件局部性?

时间:2019-04-15 20:47:35

标签: python visual-studio-code

我正在处理一个项目,在该项目中我引用的文件与palindromes.py文件位于同一文件夹中:

import load_dictionary

word_list = load_dictionary.load('words.txt')

pali_list = []

for word in word_list:
    if len(word) > 1 and word[:] == word [::-1]:
        pali_list.append(word)

print(f'\nNumber of palindromes found = {len(pali_list)}')

print(*pali_list, sep='\n')

当我在该文件夹中打开VS Code时,代码可以正常运行:

VS Code in the folder

但是,如果我在目录树的上层打开VS Code,然后向下导航,除非得到完整的路径,否则我将得到“找不到文件”:

higher up the tree

这是应该如何工作的吗?我本以为(只要我在树结构中的正确文件夹中)Python就会知道在该文件夹中运行

2 个答案:

答案 0 :(得分:0)

尝试使用“。”在开始时。例如:

word_list = load_dictionary.load('./02_finding_palingram_spells/words.txt')

答案 1 :(得分:0)

Depending on how you execute your code, your current working directory will be set to the top of your workspace, so Python thinks you're working from learning-python and not 02_finding_palingram_spells. If you're using Python 3, you can do:

import os
import pathlib

word_path = pathlib.Path(__spec__.origin).parent / "words.txt"
word_list = load_dictionary.load(os.fspath(word_path))