在本地目录中创建python文件 [英] Creating a python file in a local directory
本文介绍了在本地目录中创建python文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,所以我基本上是写一个创建文本文件的程序,只是我希望它们在与.py文件位于同一文件夹的文件夹中创建.我该怎么做? 使用python 3.3
Okay so I'm basically writing a program that creates text files except I want them created in a folder that's in this same folder as the .py file is that possibly? how do I do it? using python 3.3
推荐答案
查找脚本所在的目录:
import os
path_to_script = os.path.dirname(os.path.abspath(__file__))
然后您可以将其用作文件名:
Then you can use that for the name of your file:
my_filename = os.path.join(path_to_script, "my_file.txt")
with open(my_filename, "w") as handle:
print("Hello world!", file=handle)
这篇关于在本地目录中创建python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文