3 回答
![?](http://img1.sycdn.imooc.com/545847aa0001063202200220-100-100.jpg)
TA贡献1828条经验 获得超13个赞
您正在寻找的是相对路径,长话短说,如果您想在项目文件夹内的“TestFiles”文件夹中创建一个名为“sample.txt”的文件,您可以执行以下操作:
import os
f = open(os.path.join('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
或者使用更新的pathlib模块:
from pathlib import Path
f = open(Path('TestFiles', 'sample1.txt'), 'w')
f.write('test')
f.close()
但您需要记住,这取决于您启动 Python 解释器的位置(这可能就是您无法在项目文件夹中找到“\TestFiles'sample”的原因,它是在其他地方创建的),以确保一切正常好吧,你可以这样做:
from pathlib import Path
sample_path = Path(Path(__file__).parent, 'TestFiles', 'sample1.txt')
with open(sample_path, "w") as f:
f.write('test')
通过使用[上下文管理器]{https://book.pythontips.com/en/latest/context_managers.html},您可以避免使用f.close()
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1789条经验 获得超10个赞
创建文件时,您可以指定绝对文件名或相对文件名。如果文件路径以“\”(在 Win 上)或“/”开头,则它将是绝对路径。因此,在第一种情况下,您指定了绝对路径,实际上是:
from pathlib import Path
Path('\Testfile\'sample.txt').absolute()
WindowsPath("C:/Testfile'sample.txt")
每当你在 python 中运行一些代码时,将生成的相对路径将由你当前的文件夹组成,该文件夹是你启动 python 解释器的文件夹,你可以通过以下方式检查:
import os
os.getcwd()
以及您之后添加的相对路径,因此如果您指定:
Path('Testfiles\sample.txt').absolute()
WindowsPath('C:/Users/user/Testfiles/sample.txt')
一般来说,我建议您使用pathlib来处理路径。这使得它更安全并且跨平台。例如,假设您的凭证位于:
project
src
script.py
testfiles
并且您想要存储/读取文件project/testfiles。script.py您可以做的是获取with的路径__file__并构建到的路径project/testfiles
from pathlib import Path
src_path = Path(__file__)
testfiles_path = src_path.parent / 'testfiles'
sample_fname = testfiles_path / 'sample.txt'
with sample_fname.open('w') as f:
f.write('yo')
![?](http://img1.sycdn.imooc.com/545863f50001df1702200220-100-100.jpg)
TA贡献1788条经验 获得超4个赞
当我在 vscode 中运行第一个代码示例时,我收到一条警告 Anomalous backslash in string: '\T'. String constant might be missing an r prefix.
,当我运行该文件时,它还会创建一个名为\TestFiles'sample.txt
. 它是在.py
文件所在的同一目录中创建的。
现在,如果你的工作树是这样的:
project_folder -testfiles -sample.txt -something.py
那么你可以说:open("testfiles//hello.txt")
我希望你觉得这对你有帮助。
添加回答
举报