[英]Creating a python file in a local directory
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? 好的,我基本上是在编写一个创建文本文件的程序,只是我希望它们在与.py文件位于同一文件夹的文件夹中创建。 how do I do it?
我该怎么做? using python 3.3
使用python 3.3
To find the the directory that the script is in: 要查找脚本所在的目录:
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)
use open
: 使用
open
:
open("folder_name/myfile.txt","w").close() #if just want to create an empty file
If you want to create a file and then do something with it, then it's better to use with
statement: 如果您想创建一个文件然后对其进行处理,那么最好使用
with
语句:
with open("folder_name/myfile.txt","w") as f:
#do something with f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.