英文:
Creating a folder and writing to a file inside that folder using python
问题
I am trying to create a new folder at the location where the python script is saved and then create a new file inside that folder and write information to it. What would be the best way to create the folder and then the path for the file? Thanks a lot.
我试图在保存Python脚本的位置创建一个新文件夹,然后在该文件夹内创建一个新文件并将信息写入其中。如何最好地创建文件夹和文件的路径?非常感谢。
I used the following code to create the folder:
我使用以下代码创建文件夹:
import os
from os import path
nameofFolder = "TestFolder"
foldercheck = os.path.isdir(nameofFolder)
if foldercheck:
print('Folder present')
else:
os.makedirs(nameofFolder)
I tried using the following code to create a path for the file, but that keeps creating the file in the root directory:
我尝试使用以下代码来创建文件的路径,但这会导致文件在根目录中创建:
completepath = os.path.join(nameofFolder + "/", fileName)
英文:
I am trying to create a new folder at the location where the python script is saved and then create a new file inside that folder and write information to it.
What would be the best way to create the folder and then the path for the file?
Thanks a lot.
I used the following code to create the folder
import os
from os import path
nameofFolder = "TestFolder"
foldercheck = os.path.isdir(nameofFolder)
if foldercheck:
print('Folder present')
else:
os.makedirs(nameofFolder)
I tried using
completepath = os.path.join(nameofFolder +"/", fileName)
to create a path for the file but that keeps creating the file in the root directory.
答案1
得分: 0
创建文件夹的代码部分:
import os
currentPath = os.getcwd()
nameofFolder = "TestFolder"
if not os.path.exists(currentPath + '/' + nameofFolder):
os.makedirs(nameofFolder)
在文件夹内创建文件的代码部分:
fileName = "Hello"
f = open(nameofFolder + "/" + fileName, "w")
# 写入你想要的内容:
f.write(...)
f.close()
或者更方便的方式:
with open(nameofFolder + "/" + fileName, "w") as f:
f.write(...)
英文:
To create the folder:
import os
currentPath = os.getcwd()
nameofFolder = "TestFolder"
if not os.path.exists(currentPath + '/' + nameofFolder):
os.makedirs(nameofFolder)
To create a file inside of it:
fileName = "Hello"
f = open(nameofFolder + "/" + fileName, "w")
# writing whatever you want:
f.write(...)
f.close()
Or more conveniently:
with open(nameofFolder + "/" + fileName, "w") as f:
f.write(...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论