擅长:python、mysql、java
<p>如果需要相对路径,只需使用<code>os.path.dirname(__file__)</code>,然后使用<code>os.path.join()</code>连接路径。要在刚创建的文件夹中写入文件,只需使用相同的文件路径,如下例所示:</p>
<pre><code>import os
stuDir = 'StudentDetails'
stuDir_filepath = os.path.join(os.path.dirname(__file__), stuDir)
os.mkdir(stuDir_filepath)
facDir = 'FacultyDetails'
facDir_filepath = os.path.join(os.path.dirname(__file__), facDir)
os.mkdir(facDir_filepath)
name_of_file = "name_file"
file_path= os.path.join(facDir_filepath, name_of_file+".txt")
file1 = open(file_path, "w")
toFile = "Some Text here"
file1.write(toFile)
file1.close()
</code></pre>