簡體   English   中英

如何使用腳本的相同路徑在 VSCode 中運行 Python 腳本? (否則它找不到位於同一文件夾中的輸入文件)

[英]How to run a Python script in VSCode using the same path of the script? (otherwise it can't find an input file located in the same folder)

我有這個 Python 代碼: https : //github.com/andreagrandi/aoc_2019/tree/master/aoc如果我這樣做,它可以從終端完美運行(需要 Python 3): python aoc_03.py

但是,如果我嘗試從 VSCode 運行它,利用 Python 擴展和集成,我會收到此錯誤:

(aoc) ➜  advent_of_code_2019 git:(master) /Users/andrea/.virtualenvs/aoc/bin/python /Users/andrea/Documents/advent_of_code_2019/aoc/aoc_03.py
Traceback (most recent call last):
  File "/Users/andrea/Documents/advent_of_code_2019/aoc/aoc_03.py", line 70, in <module>
    with open('aoc_03_input.txt', 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'aoc_03_input.txt'

我的猜測是,當從 VSCode 調用時,腳本是從不同的路徑運行的,所以它找不到位於腳本同一文件夾中的文件aoc_03_input.txt

我如何告訴 VSCode 從/Users/andrea/Documents/advent_of_code_2019/aoc/文件夾運行我的腳本,以便它能夠找到我的輸入文件?

謝謝

實際上,在問這個問題之前我應該​​多嘗試一下,因為我剛剛找到了解決方案,但此時我會寫在這里,以防它對任何人有用:

如果我以這種方式更改路徑:

with open('./aoc_03_input.txt', 'r') as file:

當我在 VSCode 中運行代碼以及從終端運行它時,文件被正確打開。 在 OSX 下測試(但它也應該在 Linux 下工作。不確定 Windows)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM