有人可以帮助我吗?

huangapple go评论80阅读模式
英文:

Can someone help me?

问题

Hello,我只是Python的初学者,并且在VSC中使用Pathlib遇到了问题。所以,我根据Python Crash Course创建了这段代码:

from pathlib import Path
path = Path('pi.txt')
contents = path.read_text()
print(contents)

我收到了一个错误,说这个文件不存在。然而,当我使用'/absolute/path/to/pi.txt'指定路径时,它开始正常工作。

这段代码在PyCharm上正常工作,但有人可以解释一下为什么在VSC上不起作用吗?

英文:

Hello I am just a beginner in Python, and I got a problem with Pathlib in VSC
So, I made this code in VCS basing on Python Crash Course:

from pathlib import Path
path = Path('pi.txt')
contents = path.read_text()
print(contents)

I got an error that this file does not exist. However, when I specify the path using '/absolute/path/to/pi.txt' it starts to work.

This code works like it should on PyCharm. But, can someone explain me why this does not work on VSC?.

答案1

得分: 0

你在Visual Studio Code(VSC)中遇到的Pathlib问题可能是由于两个环境之间工作目录的差异导致的。

当你提供像pi.txt这样的相对路径时,Pathlib会假定文件位于当前工作目录中。

然而,PyCharm和VSC中的当前工作目录可能不同。要了解每个环境中的当前工作目录,你可以在现有代码之前添加以下代码:

from pathlib import Path
cwd = Path.cwd()
print(cwd)

运行这段代码将显示当前的工作目录,这将帮助你确定脚本正在查找文件的位置。

作为基本解决方案,我建议你使用基于工作目录的相对路径,如下所示:

from pathlib import Path
path = Path.cwd() / 'pi.txt'
contents = path.read_text()
print(contents)

祝你好运!

英文:

The issue you're encountering with Pathlib in Visual Studio Code (VSC) is likely due to the difference in working directories between the two environments.

When you provide a relative path like pi.txt, Pathlib assumes that the file is located in the current working directory.

However, the current working directory might not be the same in both PyCharm and VSC, To understand the current working directory in each environment, you can add the following code before your existing code:

from pathlib import Path
cwd = Path.cwd()
print(cwd)

Running this code will display the current working directory, which will help you determine where the script is looking for the file.

As a basic solution i suggest you to use a relative path based on the working directory as follow:

from pathlib import Path
path = Path.cwd() / 'pi.txt'
contents = path.read_text()
print(contents)

Best of luck mate

huangapple
  • 本文由 发表于 2023年6月28日 23:57:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76574871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定