简体   繁体   English

如何创建具有值和当前路径的.txt 文件,该文件保存在 Python 中?

[英]How to create .txt file with value and current path where this file is save in Python?

I try to create.txt file in Python I have code like below:我尝试在 Python 中创建.txt 文件我有如下代码:

with open('readme.txt', 'w') as f:
    f.write("XYZ")

And as a result I have.txt file with value: XYZ结果我有一个.txt文件,其值为: XYZ

But I need to create.txt file with values like below, so XYZ and path whete this file is created:但我需要使用如下值创建 .txt 文件,因此创建此文件的 XYZ 和路径:

XYZ
Path: "C:\Users\John\Desktop\projects\readme.txt"

How can I modify my code where I create this file so as to have as a result values presented above?如何修改我创建此文件的代码,以便获得上面显示的结果值?

you need the cwd你需要 cwd

import os
cwd = os.getcwd()

with open('readme.txt', 'w') as f:
    f.write("XYZ")
    f.write('\nPath: "'+os.getcwd()+'\\readme.txt"')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM